【发布时间】:2010-01-12 22:31:52
【问题描述】:
我正在尝试显示数字列表的所有可能排列,例如,如果我想得到 334:
3 3 4
3 4 3
4 3 3
我需要能够对最多约 12 位长度的任何一组数字执行此操作。
我确信使用 itertools.combinations 之类的东西可能相当简单,但我不能完全正确地理解语法。
TIA 山姆
【问题讨论】:
标签: python combinations
我正在尝试显示数字列表的所有可能排列,例如,如果我想得到 334:
3 3 4
3 4 3
4 3 3
我需要能够对最多约 12 位长度的任何一组数字执行此操作。
我确信使用 itertools.combinations 之类的东西可能相当简单,但我不能完全正确地理解语法。
TIA 山姆
【问题讨论】:
标签: python combinations
>>> lst = [3, 3, 4]
>>> import itertools
>>> set(itertools.permutations(lst))
{(3, 4, 3), (3, 3, 4), (4, 3, 3)}
【讨论】:
set(list()) 再次救援。
itertools.combinations。
itertools.combinations([3, 3, 4], 3) 只会产生原始集合,而不是集合中数字的排列列表(即 permutations)。
没有迭代工具
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']
【讨论】:
您需要排列,而不是组合。见:How to generate all permutations of a list in 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
【讨论】: