我正在尝试显示数字列表的所有可能排列,例如,如果我有 334 我想获得:
3 3 4
3 4 3
4 3 3
我需要能够对最多约 12 位数字的任何一组数字执行此操作。
我确信使用 itertools.combinations 之类的东西可能相当简单,但我不能完全正确地理解语法。
蒂亚山姆
我正在尝试显示数字列表的所有可能排列,例如,如果我有 334 我想获得:
3 3 4
3 4 3
4 3 3
我需要能够对最多约 12 位数字的任何一组数字执行此操作。
我确信使用 itertools.combinations 之类的东西可能相当简单,但我不能完全正确地理解语法。
蒂亚山姆
>>> lst = [3, 3, 4]
>>> import itertools
>>> set(itertools.permutations(lst))
{(3, 4, 3), (3, 3, 4), (4, 3, 3)}
没有迭代工具
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