順列,組合せ,直積でのループ

順列数や組合せ数ではなく,順列,組わせでループしたい時がある。 意外と組むのが面倒だけれど,Pythonだととても便利なライブラリが標準で与えられている。 使い方は要素となるものをリストに入れて(下の例だとa),itertoolsの,組合せ=combination, 順列= permutations, 直積=product,で簡単にループを組める。 直積は重複順列に使える。

import itertools

a = ['a', 'b', 'c']
for comb in itertools.combinations(a, r=2):
    print(comb)

for comb in itertools.permutations(a, r=2):
    print(comb)    

for comb in itertools.product(a, repeat=2):
    print(comb)