itertools: イテレータの魔法
効率的なループ処理。無限シーケンスもメモリ効率良く。
chain
複数イテラブルを連結。
product
デカルト積(直積)。
groupby
連続する同じキーでグループ化。
itertools とは?
Pythonの標準ライブラリに含まれる「イテレータ操作の決定版」です。これらを使うことで、複雑なループ処理を「簡潔」かつ「高速」かつ「メモリ効率良く」書くことができます。自力で複雑な `while` ループを書く前に、itertoolsをチェックしましょう。
import itertools
# count: 無限カウンタfor i in itertools.count(10, 2): # 10, 12, 14, ... if i > 20: break
# cycle: 無限に繰り返すcolors = itertools.cycle(['red', 'green', 'blue'])
# repeat: 同じ値を繰り返すzeros = itertools.repeat(0, 5) # [0, 0, 0, 0, 0]
# chain: 複数のイテラブルを連結combined = itertools.chain([1, 2], [3, 4]) # [1, 2, 3, 4]Bad
# ❌ Bad: ネストしたループfor a in list_a: for b in list_b: process(a, b)Good
# ✅ Good: productfrom itertools import productfor a, b in product(list_a, list_b): process(a, b)高度な関数
# permutations: 順列list(itertools.permutations('ABC', 2))# [('A','B'), ('A','C'), ('B','A'), ('B','C'), ('C','A'), ('C','B')]
# combinations: 組み合わせlist(itertools.combinations('ABC', 2))# [('A','B'), ('A','C'), ('B','C')]
# groupby: グループ化(ソート済みが前提)data = [('a', 1), ('a', 2), ('b', 3)]for key, group in itertools.groupby(data, key=lambda x: x[0]): print(key, list(group))
# islice: スライス(イテレータ用)first_10 = itertools.islice(infinite_gen, 10)
# takewhile / dropwhilepositives = itertools.takewhile(lambda x: x > 0, data) Tip: groupby はソート済みデータが前提。事前に sort() を忘れずに。
合格ライン
chain, product を使える
permutations/combinations の違いを説明できる
演習課題
課題1: chain/product
chain と product を使ってイテレータを組み合わせてください。
課題2: permutations
permutations で順列を生成してください。