본문 바로가기

책/파이썬 코딩의 기술

파이썬 코딩의 기술 - (8) 여러 이터레이터에 대해 나란히 루프를 수행하려면 zip을 사용하라

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