기본 언패킹은 언패킹할 시퀀스의 길이를 알아야 한다는 단점이 있다.
car_ages = [0, 9, 4, 8, 7, 20, 19, 1, 6, 15]
car_ages_descending = sorted(car_ages, reverse=True)
oldest, second_oldest = car_ages_descending
>>>
Traceback...
ValueError: too many values to unpack (expected 2)
oldest = car_ages+descending[0]
second_oldest = car_ages_descending[1]
others = car_ages_descending[2:]
print(oldest, second_oldest, others)
>>>
20 19 [15, 9, 8, 7, 6, 4, 1, 0]
oldest, second_oldest, *others = car_ages_descending
print(oldest, second_oldest, others)
>>>
20 19 [15, 9, 8, 7, 6, 4, 1, 0]
# oldest와 youngest만 추출
oldest, *others, youngest = car_ages_descending
print(oldest, youngest, others)
# youngest, second_youngest만 추출
*others, second_youngest, youngest = car_ages_descending
print(youngest, second_youngest, others)
>>>
20 0 [19, 15, 9, 8, 7, 6, 4, 1]
0 1 [20, 19, 15, 9, 8, 7, 6, 4]
*others = car_ages_descending
>>>
Traceback ...
SyntaxError: started assignment target must be in a list or tuple
first, *middle, *second_middle, last = [1,2,3,4]
>>>
Traceback ...
SyntaxError: two starred expressions in assignment
car_inventory = {
'시내' : ('그랜저', '아반떼', '티코'),
'공항' : ('제네시스 쿠페', '소나타', 'K5', '엑센트'),
}
((loc1, (best1, *rest1)),
(loc2, (best2, *rest2))) = car_inventory.items()
print(f'{loc1} 최고는 {best1}, 나머지는 {len(rest1)} 종'}
print(f'{loc2} 최고는 {best2}, 나머지는 {len(rest1)} 종'}
short_list = [1, 2]
first, second, *rest = short_list
print(first, second, rest)
>>>
1 2 []
def generate_csv():
yield('날짜', '제조사', '모델', '연식', '가격')
→ 비추천
all_csv_rows = list(generate_csv())
header = all_csv_rows[0]
rows = all_csv_rows[1:]
print('CSV 헤더:', header)
→ 추천
it = generate_csv()
header, *rows = it
print('CSV 헤더', header)
→ 주의점!!
* 식은 항상 리스트를 만들어 낸다 !!
만약 이터레이터를 *로 언패킹하면 컴퓨터 메모리를 모두 사용해버려서 프로그램이 다운될 수 있다. 따라서 결과 데이터를 저장할 메모리 공간이 충분할 때 나머지를 잡아내는 언패킹을 사용해야한다.