遍历数组的所有可能组合 python

Go through every possible combination of an array python

假设您有一个包含 4 个数字的数组。遍历所有可能组合的最佳方法是什么?组合的开始是:

1,2,3,4

1,2,4,3

1,3,2,4

1,3,4,2

1,4,2,3

2,1,3,4

等等

itertools.permutations 正是您要找的:

>>> from itertools import permutations
>>> [i for i in permutations(range(1, 5), 4)]
[(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]

编辑:
或者,正如@wflynny 指出的那样,您可以通过调用 list 的构造函数来保存列表理解:

>>> from itertools import permutations
>>> list(permutations(range(1, 5), 4))
[(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]

您可以使用 itertools 模块:

import itertools
arr = [1,2,3,4]
print [x for x in itertools.permutations(arr)]