假設你有一個4個數字的數組。通過所有可能的組合的最佳途徑是什麼?該組合的啓動將是:查看數組python的所有可能組合
1,2,3,4
1,2,4,3
1,3,2,4
1,3,4 ,2
1,4,2,3
2,1,3,4
等
假設你有一個4個數字的數組。通過所有可能的組合的最佳途徑是什麼?該組合的啓動將是:查看數組python的所有可能組合
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)]
你的答案可能是這裏:http://stackoverflow.com/questions/464864/python-code-to-pick-out-all-possible-combinations-from-a-list – mrcheshire
@mrcheshire不完全,我想要的是以不同順序的4個數字的所有組合。在那篇文章中,他們解釋瞭如何列出這4個數字的每個組合,與順序無關。所以1,2,3,4和1,3,2,4是一樣的。我不想成爲這種情況。 –