zip()
함수로 바로 풀면, 튜플이 unpack 되지 않아 의도대로 묶이지 않음zip()
and * operatorunpack
을 하지 않고, 그대로 zipping
하면 튜플이 풀리지 않은 채로 묶인다zip(*iterable)
로 zip object를 반환Code snippet
zipped = [('a', 1), ('b', 2)]
unzipped_object_wo_unpacking = zip(zipped)
unzipped_list_wo_unpacking = list(unzipped_object_wo_unpacking)
print(unzipped_list_wo_unpacking)
unzipped_object = zip(*zipped)
unzipped_list = list(unzipped_object)
print(unzipped_list)
Output
[(('a', 1), ), (('b', 2), )]
[('a', 'b'), (1, 2)]
Code snippet
test_list = [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]
print(test_list)
# using list comprehension to perform unzipping
unzipped_list = [[i for i, j in test_list],
[j for i, j in test_list]]
print(unzipped_list)
Output
[('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]
[('Akshat', 'Bro', 'is', 'Placed'), (1, 2, 3, 4)]
map()
사용map()
함수는 list comprehension
과 generator expression
의 도입으로 중요도 하락 및 가독성도 낮음Code snippet
test_list = [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]
print(test_list)
# using map() to perform unzipping
unzipped_list = map(None, *test_list) # basic unpacking is performed
print(unzipped_list)
Output
[('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]
[('Akshat', 'Bro', 'is', 'Placed'), (1, 2, 3, 4)]