zip()
Iterate over several iterables in parallel, producing tuples with an item from each one.
zip() returns an iterator of tuples
https://docs.python.org/3/library/functions.html#zip
Built-in Functions
The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.,,,, Built-in Functions,,, A, abs(), aiter(), all(), a...
docs.python.org
for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
print(item)
(1, 'sugar')
(2, 'spice')
(3, 'everything nice')
두 개의 이터레이터를 for 문 안에서 다루는 것보다 zip으로 처리하는 것이 가독성이 높다.
리스트 처리하는 것에 비해 장점
- 가독성
- 메모리 : lazy generator로 처리, 긴 리스트도 메모리상 문제 없이 처리 가능
주의점
두 이터레이터의 길이가 다를 때 동작에 대해 사전에 알아야함.
출력물의 길이는 가장 짧은 이터레이터의 길이와 같음
짧은 이터레이터가 아닌 긴 이터레이터 기준으로 output을 생성하고 싶은 경우
import itertools
for name, count in itertools.zip_longest(names, count):
('James', 1)
('Peter', 1)
('Homes', None)
>>> for color, c in itertools.zip_longest(colors, count, fillvalue="a"):
... print(color, c)
...
r 1
g 2
b a
'책 > 파이썬 코딩의 기술' 카테고리의 다른 글
파이썬 코딩의 기술 - (22) 변수 위치 인자를 사용해 시각적인 잡음을 줄여라 (0) | 2023.02.17 |
---|---|
파이썬 코딩의 기술 - (21) 변수 영역과 클로저의 상호작용 방식을 이해하라 (0) | 2023.02.17 |
파이썬 코딩의 기술 - (7) range보다는 enumerate를 사용하라 (0) | 2023.02.15 |