题
我想显示数字列表的所有可能的排列,例如,如果我有334我想:
3 3 4
3 4 3
4 3 3
我需要能够为任何一组数字为此至多约12位长。
我敢肯定,它可能是相当简单的使用类似itertools.combinations,但我不能完全得到语法正确。
TIA 萨姆
解决方案
>>> 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
不隶属于 StackOverflow