在 python 的列表中找到所有可能的组合序列

find all possible combination sequences in a list of python

我在 Python

中有一个列表
mylist = [0, 1, 2, 3, 4, 5]

其中 0 是开始,5 是结束。 我想知道是否有办法在 0 和 5 之间创建所有可能的序列,例如:

mylist1 = [0, 2, 1, 3, 4, 5]
mylist2 = [0, 3, 2, 1, 4, 5]
mylist3 = [0, 4, 3, 2, 1, 5]
mylist4 = [0, 2, 1, 3, 4, 5]
mylist5 = [0, 3, 2, 1, 4, 5]

等等

你应该使用 itertools.permutations,像这样:

import itertools
gen = itertools.permutations([1, 2, 3, 4, 5, 6])
print gen.next()  # prints (1, 2, 3, 4, 5, 6)
print gen.next()  # prints (1, 2, 3, 4, 6, 5)
print gen.next()  # prints (1, 2, 3, 5, 4, 6)

继续这样做,直到 StopIteration 出现。

您可以使用itertools.permutations

In [1]: import itertools

In [2]: l = [0, 1, 2, 3, 4, 5]

In [3]: tuple(itertools.permutations(l))
Out[3]: 
((0, 1, 2, 3, 4, 5),
 (0, 1, 2, 3, 5, 4),
 (0, 1, 2, 4, 3, 5),
 (0, 1, 2, 4, 5, 3),
 (0, 1, 2, 5, 3, 4),
 ....