Python获得数字的所有排列

时间:2010-01-12 22:31:52

标签: python combinations

我正在尝试显示数字列表的所有可能排列,例如,如果我有334我想要获得:

3 3 4
3 4 3
4 3 3

我需要能够为长达12位左右的任何数字组执行此操作。

我确信使用像itertools.combinations这样的东西可能相当简单,但我无法正确理解语法。

TIA 萨姆

4 个答案:

答案 0 :(得分:27)

>>> lst = [3, 3, 4]
>>> import itertools
>>> set(itertools.permutations(lst))
{(3, 4, 3), (3, 3, 4), (4, 3, 3)}

答案 1 :(得分:4)

没有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']

答案 2 :(得分:2)

您想要排列,而不是组合。请参阅: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(这在数学上是正确的),但与您的示例不同。如果列表中有重复的数字,这只会产生影响。

答案 3 :(得分:1)

我使用python的itertools,但是如果你必须自己实现这个,这里的代码返回指定大小的所有排列值。

示例:values = [1,2,3]size = 2 =&gt; [[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
相关问题