Python/공부

파이썬 itertools 함수 iterator의 종류

끈끈 2023. 3. 23. 14:52

 

itertools

 

파이썬3의 표준 라이브러리로, 효율적인 루핑을 위한 이터레이터를 만드는 함수

 

루프(Loop):

 

반복문. 명령문을 반복적으로 실행시키는 것

 

이터레이터(Iterator)

 

파이썬에서 반복으로 처리를 수행할 수 있는 모든 객체

 

대표적으로는 for, comprehesion, map 등이 있다

 

👇 이터레이터의 종류와 예시

 

https://docs.python.org/ko/3/library/itertools.html

 

itertools — Functions creating iterators for efficient looping

This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python. The module standardizes a core set...

docs.python.org

 

iter 함수는 next 함수와 같이 사용되는 경우가 많다

 

iter를 이용해 이터레이터를 만들고 next로 반복을 수행하도록 요청한다

 

더 이상 가져올 게 없으면 StopIteration이 발생한다

 


 

이터레이터에는 무한, 종료, 조합형 이터레이터가 있는데,

 

그 중 조합형 이터레이터에 대해 살펴보겠다

 

product, permutations, combinations, combinations_with_replacement

 

product()

 

데카르트 곱(각 집합의 원소를 각 성분으로 하는 튜플들의 집합)을 구할 때 쓰인다

 

from itertools import product

 

 

 

enumerate(product() , 1)를 통해 표의 형태로 뽑아낸다 (start = int 1)

 

repeat=1 기본값은 1인데 반복 횟수를 지정해 줄 수 있다

 

permutations()

 

from itertools import permutations

 

최대 2개의 인수를 받는다

 

 

combinations()

 

from itertools import combinations

 

 

combinations_with_replacement()

 

from itertools import combinations_with_replacement

 

 

네가지의 조합형 이터레이터가 비슷해 보여서 헷갈렸는데

 

아래 표를 보니 조금은 이해가 되었다

 

출처 : itertools