본문으로 바로가기

itertools

  • itertools 모듈은 다양한 이터레이터를 생성하는 함수를 지원한다.

 

 

예제 1

 

combinations() 함수는 요소에 대한 중복없는 순서쌍 이터레이터를 생성합니다.

import collections
import itertools as it

color = ['red', 'yellow', 'green', 'blue']

for combi in it.combinations(color, 2):
    print(combi)

combi = it.combinations(color, 3)
print(type(combi))

print(isinstance(combi, collections.Iterable))
print(isinstance(combi, collections.Iterator))

print(next(combi))
print(next(combi))
('red', 'yellow')
('red', 'green')
('red', 'blue')
('yellow', 'green')
('yellow', 'blue')
('green', 'blue')
<class 'itertools.combinations'>
True
True
('red', 'yellow', 'green')
('red', 'yellow', 'blue')

 

 

예제 2

 

permutations() 함수는 모든 조합의 순서쌍 이터레이터를 생성합니다.

요소에 대한 중복은 있으나, 요소 순서에 대한 중복은 없습니다.

import itertools as it

color = ['red', 'yellow', 'green', 'blue']

for combi in it.permutations(color, 3):
    print(combi)
('red', 'yellow', 'green')
('red', 'yellow', 'blue')
('red', 'green', 'yellow')
('red', 'green', 'blue')
('red', 'blue', 'yellow')
('red', 'blue', 'green')
('yellow', 'red', 'green')
('yellow', 'red', 'blue')
('yellow', 'green', 'red')
('yellow', 'green', 'blue')
('yellow', 'blue', 'red')
('yellow', 'blue', 'green')
('green', 'red', 'yellow')
('green', 'red', 'blue')
('green', 'yellow', 'red')
('green', 'yellow', 'blue')
('green', 'blue', 'red')
('green', 'blue', 'yellow')
('blue', 'red', 'yellow')
('blue', 'red', 'green')
('blue', 'yellow', 'red')
('blue', 'yellow', 'green')
('blue', 'green', 'red')
('blue', 'green', 'yellow')

 

 

기타

 

chain() 함수는 반복형 객체들을 연결합니다.

import itertools as it

color = ['red', 'yellow', 'green', 'blue']
color2 = ['yellow', 'pink', 'black']
color3 = ['brown', 'white', 'purple']

for c in it.chain(color, color2, color3):
    print(c)
red
yellow
green
blue
yellow
pink
black
brown
white
purple

 

zip_longest() 함수는 두 반복 객체를 묶어줍니다.

내장함수 zip 과 비교하면 다음과 같은 차이가 있습니다.

import itertools as it

color = ['red', 'yellow', 'green', 'blue']
color2 = ['yellow', 'pink', 'black']

for c1, c2 in zip(color, color2):
    print(c1, c2)

print()

for c1, c2 in it.zip_longest(color, color2):
    print(c1, c2)
red yellow
yellow pink
green black

red yellow
yellow pink
green black
blue None

 

 

참고

 

itertools --- 효율적인 루핑을 위한 이터레이터를 만드는 함수 — 파이썬 설명서 주석판

 

python.flowdas.com