PHpullh

PYTHON · 컬렉션

itertools 활용

itertoolschain, product, permutations 등으로 효율적인 이터레이션을 수행합니다.

컬렉션중급itertoolschainproductpermutations

핵심 설명

itertoolschain, product, permutations 등으로 효율적인 이터레이션을 수행합니다.

Python code

from itertools import chain, product, permutations, combinations

# chain: 여러 이터러블 연결
a = [1, 2, 3]
b = [4, 5, 6]
print(list(chain(a, b)))  # [1, 2, 3, 4, 5, 6]

# product: 데카르트 곱
colors = ["빨강", "파랑"]
sizes = ["S", "M", "L"]
for color, size in product(colors, sizes):
    print(f"  {color}-{size}", end="")
print()

# permutations: 순열
print(list(permutations([1, 2, 3], 2)))
# [(1,2), (1,3), (2,1), (2,3), (3,1), (3,2)]

# combinations: 조합
print(list(combinations([1, 2, 3, 4], 2)))
# [(1,2), (1,3), (1,4), (2,3), (2,4), (3,4)]

# accumulate: 누적 연산
from itertools import accumulate
import operator
data = [1, 2, 3, 4, 5]
print(list(accumulate(data)))                  # 누적 합
print(list(accumulate(data, operator.mul)))    # 누적 곱

학습 팁

itertools 함수는 지연 평가(lazy)되므로 메모리 효율적입니다. 큰 데이터셋에 적합합니다.

주의할 점

permutationscombinations는 큰 입력에 대해 결과가 폭발적으로 증가합니다. n=20이면 순열은 약 2.4×10¹⁸개입니다.

자주 묻는 질문

itertools 활용란 무엇인가요?

itertools 의 chain , product , permutations 등으로 효율적인 이터레이션을 수행합니다.

itertools 활용 학습 시 주의할 점은 무엇인가요?

permutations 과 combinations 는 큰 입력에 대해 결과가 폭발적으로 증가합니다. n=20이면 순열은 약 2.4×10¹⁸개입니다.