【问题标题】:Python get all permutations of numbersPython获取数字的所有排列
【发布时间】:2010-01-12 22:31:52
【问题描述】:

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

3 3 4
3 4 3
4 3 3

我需要能够对最多约 12 位长度的任何一组数字执行此操作。

我确信使用 itertools.combinations 之类的东西可能相当简单,但我不能完全正确地理解语法。

TIA 山姆

【问题讨论】:

    标签: python combinations


    【解决方案1】:
    >>> lst = [3, 3, 4]
    >>> import itertools
    >>> set(itertools.permutations(lst))
    {(3, 4, 3), (3, 3, 4), (4, 3, 3)}
    

    【讨论】:

    • +1,列表的不同排列。 set(list()) 再次救援。
    • @Seth 请改用itertools.combinations
    • @nbro - 组合和排列是不同的操作(但相关)。在这种情况下,itertools.combinations([3, 3, 4], 3) 只会产生原始集合,而不是集合中数字的排列列表(即 permutations)。
    【解决方案2】:

    没有迭代工具

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

    【讨论】:

    • 正在遵循这种方法,但无法理解这两个循环实际上在做什么。您会在答案中添加一些文字吗?
    【解决方案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(这在数学上是正确的做法),但与您的示例不同。只有当您的列表中有重复的数字时,这才会有所作为。

    【讨论】:

      【解决方案4】:

      我会使用 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
      

      【讨论】:

      • 这是一个很酷的答案,我喜欢,但如果 values 也支持零可能会很好。例如:values = [0,1,2] 这个逻辑失败了。 :)
      猜你喜欢
      • 1970-01-01
      • 2017-05-03
      • 2012-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      相关资源
      最近更新 更多