[英]Python get all permutations of numbers
我试图显示数字列表的所有可能的排列,例如,如果我有334我想得到:
3 3 4
3 4 3
4 3 3
我需要能够为任何长达12位左右的数字组执行此操作。
我确信使用像itertools.combinations这样的东西可能相当简单,但是我不能完全正确地使用语法。
TIA Sam
>>> lst = [3, 3, 4]
>>> import itertools
>>> set(itertools.permutations(lst))
{(3, 4, 3), (3, 3, 4), (4, 3, 3)}
没有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']
你想要排列,而不是组合。 请参阅: 如何在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(这在数学上是正确的),但与您的示例不同。 如果列表中有重复的数字,这只会产生影响。
我会使用python的itertools
,但是如果你必须自己实现这个,这里的代码返回指定大小的所有排列值。
示例: values = [1,2,3]
, size = 2
=> [[3, 2], [2, 3], [2, 1], [3, 1], [1, 3], [1, 2]]
def permutate(values, size):
return map(lambda p: [values[i] for i in p], permutate_positions(len(values), size))
def permutate_positions(n, size):
if (n==1):
return [[n]]
unique = []
for p in map(lambda perm: perm[:size], [ p[:i-1] + [n-1] + p[i-1:] for p in permutate_positions(n-1, size) for i in range(1, n+1) ]):
if p not in unique:
unique.append(p)
return unique
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.