itertools
1. itertools の概要
効率的なループ実行のためのイテレータ生成関数モジュール
for文と併用することが多い
利用前に importする
2. 競技プログラミングで便利なモジュール
(1) 順列 permutations
リストや文字列の要素に対する順列を全列挙する
例:0~2の3個の数値の全列挙
code: python
from itertools import permutations
for order in permutations(range(3)):
print(order)
# (0, 1, 2)
# (0, 2, 1)
# (1, 0, 2)
# (1, 2, 0)
# (2, 0, 1)
# (2, 1, 0)
例:リストの要素の全列挙(上の方法を利用)
code: python
from itertools import permutations
names = 'Aoki', 'Inoue', 'Ueno'
for order in permutations(range(3)):
print(names[order0], names[order1], names[order2])
# print(*[namesi for i in order]) でも可
# Aoki Inoue Ueno
# Aoki Ueno Inoue
# Inoue Aoki Ueno
# Inoue Ueno Aoki
# Ueno Aoki Inoue
# Ueno Inoue Aoki
例:リストの要素の全列挙(リストそのものを利用.出力結果は上と同じ)
code: python
from itertools import permutations
names = 'Aoki', 'Inoue', 'Ueno'
for order in permutations(names):
print(order0, order1, order2)
# print(*order) でも可
例:文字列の並び方の全列挙
code: python
from itertools import permutations
for order in permutations('abc'):
print(order)
# ('a', 'b', 'c')
# ('a', 'c', 'b')
# ('b', 'a', 'c')
# ('b', 'c', 'a')
# ('c', 'a', 'b')
# ('c', 'b', 'a')
(2) 組合せ combinatoins
リストや文字列に対する組合せを全列挙する
例:0~4の4個の数値から全てのペアを選ぶ
code: python
from itertools import combinations
for order in combinations(range(4), 2):
print(order)
# (0, 1)
# (0, 2)
# (0, 3)
# (1, 2)
# (1, 3)
# (2, 3)
例:上の例で,ペアとなる数を変数 i, jに代入.2重ループを1行で書ける.
code: python
from itertools import combinations
for i, j in combinations(range(4), 2):
print(i, j)
# 0 1
# 0 2
# 0 3
# 1 2
# 1 3
# 2 3
例:リスト内のすべてのペアを列挙
code: python
from itertools import combinations
names = 'Aoki', 'Inoue', 'Ueno'
for pair in combinations(names, 2):
print(pair)
# ('Aoki', 'Inoue')
# ('Aoki', 'Ueno')
# ('Inoue', 'Ueno')
例:文字列でもできる.選択数も3以上でもOK
code: python
from itertools import combinations
for pair in combinations('abcd', 3):
print(pair)
# ('a', 'b', 'c')
# ('a', 'b', 'd')
# ('a', 'c', 'd')
# ('b', 'c', 'd')
【参考】似たようなモジュールで,重複選択を許す combinations_with_replacementもある
code: python
from itertools import combinations_with_replacement
for pair in combinations_with_replacement('abcd', 2):
print(pair)
# ('a', 'a')
# ('a', 'b')
# ('a', 'c')
# ('a', 'd')
# ('b', 'b')
# ('b', 'c')
# ('b', 'd')
# ('c', 'c')
# ('c', 'd')
# ('d', 'd')
(3) 直積 product
複数のリスト等から,1つずつ選択する組合せを列挙
例:文字列とrangeの組合せ
code: python
from itertools import product
for order in product('AB', range(3), 'XY'):
print(order)
# ('A', 0, 'X')
# ('A', 0, 'Y')
# ('A', 1, 'X')
# ('A', 1, 'Y')
# ('A', 2, 'X')
# ('A', 2, 'Y')
# ('B', 0, 'X')
# ('B', 0, 'Y')
# ('B', 1, 'X')
# ('B', 1, 'Y')
# ('B', 2, 'X')
# ('B', 2, 'Y')
例:同じ数値の範囲の組合せ.二重ループを1行で書ける
code: python
from itertools import product
for i, j in product(range(3), repeat=2):
print(i, j)
# 0 0
# 0 1
# 0 2
# 1 0
# 1 1
# 1 2
# 2 0
# 2 1
# 2 2
3. その他
数値リストを累積に変換: accumurate
連続する同じ要素をまとめる:groupby などなど.詳しくは参考ページ
参考:
itertools --- 効率的なループ実行のためのイテレータ生成関数 https://docs.python.org/ja/3/library/itertools.html
すごいぞitertoolsくん https://qiita.com/anmint/items/37ca0ded5e1d360b51f3
#モジュール #ジェネレータ