关于python:如何创建一个程序,显示所有可能的组合

how to create a program that show you all the possible combinations

本问题已经有最佳答案,请猛点这里访问。

我需要帮助在python中创建一个显示所有可能组合的程序。例如:我给它编号"1 2 3"我给了我"1 3 2","3 2 1","3 1 2","2 1 3","2 3 1"。


使用itertools。它使生活变得容易:

1
2
3
4
5
6
7
8
9
10
11
12
13
import itertools

perms = itertools.permutations([1,2,3])

for perm in perms:
    print perm

>>>(1, 2, 3)
>>>(1, 3, 2)
>>>(2, 1, 3)
>>>(2, 3, 1)
>>>(3, 1, 2)
>>>(3, 2, 1)


1
2
3
4
5
6
7
from itertools import combinations as c
for x in c([1, 2, 3],2): print x
(1, 2)
(1, 3)
(2, 3)
print [x for x in c(range(5), 3)]                                        
[(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]