PYTHON · 성능
itertools — 고성능 이터레이터
표준 라이브러리 itertools로 메모리 효율적인 데이터 처리를 구현합니다.
성능고급itertoolschaingroupbyproductcombinations
핵심 설명
표준 라이브러리 itertools로 메모리 효율적인 데이터 처리를 구현합니다.
Python code
import itertools
# count, cycle, repeat — 무한 이터레이터
counter = itertools.count(start=1, step=2) # 1, 3, 5, 7...
first5 = list(itertools.islice(counter, 5)) # [1, 3, 5, 7, 9]
# chain — 여러 이터러블 연결
combined = list(itertools.chain([1,2], [3,4], [5,6]))
# [1, 2, 3, 4, 5, 6]
# batched (Python 3.12+) — N개씩 묶기
data = range(10)
batches = list(itertools.batched(data, 3))
# [(0,1,2), (3,4,5), (6,7,8), (9,)]
# groupby — 연속된 같은 값 그룹화
data = [("A",1),("A",2),("B",3),("B",4),("A",5)]
for key, group in itertools.groupby(data, key=lambda x: x[0]):
print(key, list(group))
# product — 카르테시안 곱
for r, g, b in itertools.product([0,255], repeat=3):
pass # 8개 색상 조합
# combinations / permutations
items = [1, 2, 3, 4]
combs = list(itertools.combinations(items, 2))
perms = list(itertools.permutations(items, 2))
print(f"조합: {len(combs)}개, 순열: {len(perms)}개")
# accumulate — 누적 연산
cumsum = list(itertools.accumulate([1,2,3,4,5]))
# [1, 3, 6, 10, 15]
import operator
cumprod = list(itertools.accumulate([1,2,3,4,5], operator.mul))
# [1, 2, 6, 24, 120]학습 팁
itertools의 함수들은 모두 이터레이터를 반환합니다. 결과를 리스트로 필요할 때만 list()로 변환하세요.
주의할 점
itertools.groupby()는 연속된 같은 값만 그룹화합니다. 전체 그룹화가 필요하면 먼저 정렬하거나 defaultdict를 사용하세요.
자주 묻는 질문
itertools — 고성능 이터레이터란 무엇인가요?
표준 라이브러리 itertools 로 메모리 효율적인 데이터 처리를 구현합니다.
itertools — 고성능 이터레이터 학습 시 주의할 점은 무엇인가요?
itertools.groupby() 는 연속된 같은 값만 그룹화합니다. 전체 그룹화가 필요하면 먼저 정렬하거나 defaultdict 를 사용하세요.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.