** TIL at 220720
numbers = (1, 2, 3, 4, 5) # 패킹
print(numbers) # (1, 2, 3, 4, 5)
numbers = (1, 2, 3, 4, 5)
a, b, c, d, e = numbers # 언패킹
print(a, b, c, d, e) # 1 2 3 4 5
*
)를 붙이면, 할당하고 남은 요소를 리스트에 담을 수 있음numbers = (1, 2, 3, 4, 5)
a, b, *rest = numbers
print(a, b, rest) # 1 2 [3, 4, 5]
a, *rest, e = numbers
print(a, rest, e) # 1 [2, 3, 4] 5
*
는 시퀀스 언패킹 연산자 (시퀀스를 풀어 헤치는 연산자)def func(*args):
print(args)
print(type(args))
func(1, 2, 3, 'a', 'b')
'''
(1, 2, 3, 'a', 'b')
<class 'tuple'>
'''
: 반드시 받아야하는 인자와, 추가적인 인자를 구분해서 사용할 수 있다.
def print_family_name(father, mother, *pets):
print(father)
print(mother)
print(pets)
...
print_family_name('아부지', '어머니', '멍멍이', '야옹이')
**kwargs
는 딕셔너리로 묶어 처리def family(**kwargs):
for key, value in kwargs.items():
print(key, ":", value)
print(father='아빠', mother='엄마', baby='아가')
'''
father : 아빠
mother : 엄마
baby : 아가
'''
def print_family_name(*parents, **pets):
print('아버지 :', parents[0])
print('어머니 :', parents[1])
if pets:
print('반려동물들..')
for title, name in pets.items():
print('{} : {}'.format(title, name))