ofutonneko

情弱がんばる自分用めも

Python3でリストやタプルの要素の並びを全通り列挙する

リストの要素の並び替えを全通り列挙したい時は、itertools.permutations(l)とすればOK。 タプルでも同様に可。

>>> import itertools
>>> l = ['a', 'b', 'c']
>>> for i in itertools.permutations(l):
...   print(i)
...
('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')

そのものはitertools.permutationsオブジェクト。

>>> itertools.permutations(l)
<itertools.permutations object at 0x10c5fc3b0>

出力したかったらキャストしたりしないといけない。

>>> list(itertools.permutations(l))
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]