itertools: イテレータの魔法

効率的なループ処理。無限シーケンスもメモリ効率良く。

chain
複数イテラブルを連結。
product
デカルト積(直積)。
groupby
連続する同じキーでグループ化。

itertools とは?

シェフの万能調理器具 (Chef's Kitchen Gadgets)

リスト(食材)をfor文(包丁)で切るのは基本的ですが、効率が悪いです。itertoolsは「フードプロセッサー」や「製麺機」のようなプロ用調理器具セットです。複数の食材を瞬時に繋げたり(chain)、全ての組み合わせを試作したり(product)、無限に麺を出し続けたり(count)できます。プロの厨房(高度な処理)には欠かせません。

Pythonの標準ライブラリに含まれる「イテレータ操作の決定版」です。これらを使うことで、複雑なループ処理を「簡潔」かつ「高速」かつ「メモリ効率良く」書くことができます。自力で複雑な `while` ループを書く前に、itertoolsをチェックしましょう。

Basic 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: product
from itertools import product
for a, b in product(list_a, list_b):
process(a, b)

高度な関数

permutations, combinations, groupby
# 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 / dropwhile
positives = itertools.takewhile(lambda x: x > 0, data)
Tip: groupby はソート済みデータが前提。事前に sort() を忘れずに。

合格ライン

chain, product を使える
permutations/combinations の違いを説明できる

演習課題

課題1: chain/product
chain と product を使ってイテレータを組み合わせてください。
課題2: permutations
permutations で順列を生成してください。