Python itertools ライブラリ完全ガイド
Python 標準ライブラリの itertools は、反復処理(イテレーション)を効率的に行うための便利なツールを提供します。本記事では、itertools の主要な機能とその活用方法について詳しく解説します。
1. itertools ライブラリの概要
itertoolsは、イテレータを操作するための関数を提供します。- ループ処理を効率化し、メモリ効率の良いコードを記述するのに役立ちます。
- 組み合わせ・順列の生成、無限イテレータ、フィルタリング機能などを備えています。
インストール方法
itertools は Python の標準ライブラリなので、追加のインストールは不要です。
import itertools
import itertools
# count: 1 ずつ増加する無限ループ
take_5 = list(itertools.islice(itertools.count(10, 2), 5))
print(take_5) # [10, 12, 14, 16, 18]
# cycle: 指定したシーケンスを無限ループ
cycler = itertools.cycle(["A", "B", "C"])
print([next(cycler) for _ in range(6)]) # ['A', 'B', 'C', 'A', 'B', 'C']
# repeat: 同じ値を繰り返す
print(list(itertools.repeat("X", 4))) # ['X', 'X', 'X', 'X']
import itertools
items = ['A', 'B', 'C']
# 順列(並べ替え)
print(list(itertools.permutations(items, 2))) # [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
# 組み合わせ(順番は考慮しない)
print(list(itertools.combinations(items, 2))) # [('A', 'B'), ('A', 'C'), ('B', 'C')]
# 重複を許可する組み合わせ
print(list(itertools.combinations_with_replacement(items, 2))) # [('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]
import itertools
nums = [1, 2, 3, 4, 5, 6]
# 条件に合わないものを抽出(偶数を抽出)
print(list(itertools.filterfalse(lambda x: x % 2, nums))) # [2, 4, 6]
# 条件が True の間スキップ
print(list(itertools.dropwhile(lambda x: x < 4, nums))) # [4, 5, 6]
# 条件が True の間取得
print(list(itertools.takewhile(lambda x: x < 4, nums))) # [1, 2, 3]
import itertools
data = [("A", 1), ("A", 2), ("B", 3), ("B", 4), ("C", 5)]
for key, group in itertools.groupby(data, key=lambda x: x[0]):
print(key, list(group))
import itertools
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# 2つのリストを連結
print(list(itertools.chain(list1, list2))) # [1, 2, 3, 4, 5, 6]
import itertools
colors = ["red", "blue"]
sizes = ["S", "M", "L"]
# 直積を生成
print(list(itertools.product(colors, sizes)))
import itertools
numbers = [1, 2, 3, 4]
print(list(itertools.accumulate(numbers))) # [1, 3, 6, 10]
import itertools
iterator = iter([1, 2, 3])
iter1, iter2 = itertools.tee(iterator, 2)
print(list(iter1)) # [1, 2, 3]
print(list(iter2)) # [1, 2, 3]
import itertools
import operator
pairs = [(1, 2), (3, 4), (5, 6)]
print(list(itertools.starmap(operator.mul, pairs))) # [2, 12, 30]
import itertools
# Python 3.10 以降で利用可能
def batched(iterable, n):
it = iter(iterable)
while batch := tuple(itertools.islice(it, n)):
yield batch
print(list(batched(range(10), 3))) # [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9,)]