Python의 빌트인 함수인 zip()둘 이상의 iterable 객체를 한 번에 순회하기 위해 사용합니다.

zip(*iterables)

인자로 전달된 각 iterable을 집계한 tuple iterator를 반환합니다. i번째 tuple에는 iterable 각각의 i번째 요소가 들어 있습니다.

l1 = [1, 2, 3, 4, 5]
l2 = [6, 7, 8, 9, 10]
zipped = zip(l1, l2)
print(list(zipped))
# [(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
for a, b in zipped:
print(a, b)
# 1 6
# 2 7
# ...
# 5 10
view raw zip.py hosted with ❤ by GitHub

zip()은 인자로 전달된 가장 짧은 iterable 객체가 모두 소모되면 멈춥니다.

l1 = [1, 2, 3, 4, 5]
l2 = [6, 7, 8]
for a, b in zip(l1, l2):
print(a, b)
# 1 6
# 2 7
# 3 8
view raw zip-shortest.py hosted with ❤ by GitHub

가장 긴 iterable 객체를 기준으로 zip을 수행하려면, Python 표준 라이브러리인 itertools를 사용해야 합니다.

'Python 계열 > Python 레거시 글' 카테고리의 다른 글

Context Manager  (0) 2018.11.01
Argument Unpacking  (0) 2018.10.30
[Python] Coroutines  (0) 2018.07.27
[Python] memoize  (0) 2018.07.26
[Python] Assert  (0) 2018.07.25

+ Recent posts