Python获取所有数字的排列
我想把一组数字的所有可能排列都显示出来,比如如果我有334,我希望得到:
3 3 4
3 4 3
4 3 3
我需要能够对任何最多12位的数字组合这样做。
我觉得用像itertools.combinations这样的工具应该很简单,但我就是搞不清楚怎么写代码。
谢谢大家!
萨姆
4 个回答
3
你想要的是排列,而不是组合。可以参考这个链接:如何在Python中生成一个列表的所有排列
>>> from itertools import permutations
>>> [a for a in permutations([3,3,4])]
[(3, 3, 4), (3, 4, 3), (3, 3, 4), (3, 4, 3), (4, 3, 3), (4, 3, 3)]
注意,这里是在对两个3进行排列(这是数学上正确的做法),但和你的例子不一样。只有当你的列表中有重复的数字时,这个差别才会显现出来。
5
不使用itertools
def permute(LIST):
length=len(LIST)
if length <= 1:
yield LIST
else:
for n in range(0,length):
for end in permute( LIST[:n] + LIST[n+1:] ):
yield [ LIST[n] ] + end
for x in permute(["3","3","4"]):
print x
输出结果
$ ./python.py
['3', '3', '4']
['3', '4', '3']
['3', '3', '4']
['3', '4', '3']
['4', '3', '3']
['4', '3', '3']
26
>>> lst = [3, 3, 4]
>>> import itertools
>>> set(itertools.permutations(lst))
{(3, 4, 3), (3, 3, 4), (4, 3, 3)}
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。