1. 함수를 콜할 때 인자로 전달되는 iterable 객체를 unpacking
animal = ['monkey', 'giraffe', 'lion', 'elephant']
print(animal[0], animal[1], animal[2], animal[3])
monkey giraffe lion elephant
print(*animal)
monkey giraffe lion elephant
○ 2차원 배열 전치행렬
n = [[1, 4], [2, 5], [3, 6]]
print(*n, sep='\n')
[1, 4]
[2, 5]
[3, 6]
n2 = [list(row) for row in zip(*n)]
print(*n2, sep='\n')
[1, 2, 3]
[4, 5, 6]
zip(*n)은 n을 unpacking 후
zip함수의 인자로 [1, 4], [2, 5], [3, 6] 3개의 리스트로 전달.
zip은 (1,2,3) (4,5,6) 으로 묶음.
○ dictionary의 unpacking에 ** 을 사용
d = {'yy': "2021", 'mm': "06", 'dd': "26"}
fname = "{yy}.{mm}.{dd}.txt".format(**d)
print(fname)
2021.06.26.txt
2. 함수에서 unlimited 갯수의 인수를 packing (튜플로 받음)
def add(*n):
return sum(x for x in n)
print(add(1))
print(add(1,2,3))
print(add(1,2,3,4,5,6,7,8,9,10))
1
6
55
○ 함수에서 unlimited 갯수의 키워드 인수를 딕셔너리로 packing해 받을 때 ** 을 사용
def tag(tag_nm, **attributes):
l = [f'{nm}="{val}"' for nm, val in attributes.items()]
return f"<{tag_name} {' '.join(l)}>"
print(tag('a', href="http://tistory.com"))
print(tag('img', height=20, width=20, src="miraflores.jpg"))
<a href="http://tistory.com">
<img height="20" width="20" src="miraflores.jpg">
3. 튜플( or 리스트) Unpacking시의 Asterisks(*) - 변수할당
cities = ('seoul','moscow','madrid','paris')
first, second, *remaining = cities
print(remaining)
['madrid', 'paris']
first, *remaining = cities
print(remaining)
['moscow', 'madrid', 'paris']
first, *middle, last = cities
print(middle)
['moscow', 'madrid']
((first_letter, *remaining), *other_cities) = cities
print(remaining)
['e', 'o', 'u', 'l']
print(other_cities)
['moscow', 'madrid', 'paris']
4. list literals에서 Asterisks(*)
#palindrom 만들기
def palindrom(seq):
return list(seq)+ list(reversed(seq))
def palindrom2(seq):
return [*seq, *reversed(seq)] # *를빼고 수행해보면 * 이 왜 필요한지 알게 됨.
print(palindrom((1,2,3,4,5)))
print(palindrom2((1,2,3,4,5)))
[1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
#리스트의 첫번째 아이템을 맨 뒤로 보내면서 튜플로 생성
cities = ['seoul','moscow','madrid','paris']
print((*cities[1:], cities[0]))
('moscow', 'madrid', 'paris', 'seoul')
#리스트의 아이템을 대문자화 해서 set 생성
upper_cities = (c.upper() for c in cities)
print({*cities, *upper_cities})
{'MADRID', 'PARIS', 'paris', 'seoul', 'SEOUL', 'MOSCOW', 'madrid', 'moscow'} # 순서는 random임
https://treyhunner.com/2018/10/asterisks-in-python-what-they-are-and-how-to-use-them/
'Python' 카테고리의 다른 글
백준 7490 0 만들기 (0) | 2024.05.12 |
---|---|
bisect (0) | 2024.04.21 |
파이썬 리스트 (0) | 2021.07.08 |
Python 승수 연산의 속도 (**연산자, *반복사용, pow()함수) (0) | 2021.07.04 |
:= 바다코끼리 연산자(the walrus operator) (0) | 2021.07.04 |