Python itertools

김신영·2025년 5월 1일

Python

목록 보기
4/10
post-thumbnail
기능함수설명
순열permutations순서 O, 중복 X
조합combinations순서 X, 중복 X
중복 조합combinations_with_replacement순서 X, 중복 O
데카르트 곱product중첩 루프를 간단히 처리
슬라이스islice이터레이터 슬라이싱
무한 카운터count무한 반복 (start부터 step씩 증가)
필터링filterfalse조건이 거짓인 것만 추출
순환cycle반복해서 순환
고정반복repeat특정 값 반복
그룹핑groupby연속된 값 기준 그룹핑

1. 순열 / 조합 관련

permutations(iterable, r)

  • 순열 (모든 경우의 순서 있는 조합)
from itertools import permutations
list(permutations([1, 2, 3], 2))  # [(1,2), (1,3), (2,1), (2,3), ...]

combinations(iterable, r)

  • 조합 (순서 없는 r개 선택)
from itertools import combinations
list(combinations([1, 2, 3], 2))  # [(1,2), (1,3), (2,3)]

combinations_with_replacement(iterable, r)

  • 중복 조합
list(combinations_with_replacement([1, 2], 2))  # [(1,1), (1,2), (2,2)]

2. 중첩 반복

product(*iterables, repeat=1)

  • 데카르트 곱 (이중/삼중 루프 대신)
from itertools import product
list(product([0, 1], repeat=2))  # [(0,0), (0,1), (1,0), (1,1)]

3. 무한 반복자

count(start=0, step=1)

  • 무한 카운터
from itertools import count
for i in count(10, 2):  # 10, 12, 14, ...
    if i > 20:
        break
    print(i)

cycle(iterable)

  • 반복해서 순환
from itertools import cycle
c = cycle('AB')
[next(c) for _ in range(5)]  # ['A', 'B', 'A', 'B', 'A']

repeat(elem, n)

  • 특정 값을 n번 반복
from itertools import repeat
list(repeat(3, 4))  # [3, 3, 3, 3]

4. 조건 / 필터링 관련

islice(iterable, start, stop, step)

  • 슬라이싱 (iterable에서 가능)
from itertools import islice
list(islice(range(100), 10, 20, 2))  # [10, 12, 14, 16, 18]

filterfalse(predicate, iterable)

  • 조건이 False인 것만 남김
from itertools import filterfalse
list(filterfalse(lambda x: x%2, range(5)))  # [0, 2, 4]

5. 그룹핑/집계 관련

groupby(iterable, key=...)

  • 연속된 같은 값을 그룹핑
from itertools import groupby
data = 'AAABBCCDAA'
grouped = [(k, list(g)) for k, g in groupby(data)]
# [('A', ['A', 'A', 'A']), ('B', ['B', 'B']), ...]

요약

기능기본 내장 코드itertools 코드메모리 효율속도 효율
조건 필터링 (True)filter(func, iterable)동일
조건 필터링 (False)x for x in ... if notfilterfalse(func, iterable)
슬라이스 (이터레이터용)안됨 (list() 필요)islice(iterable, start, stop, step)
순열/조합/곱직접 구현해야 함permutations, product
profile
Hello velog!

0개의 댓글