在python中生成列表的所有组合

Min*_*yan 24 python combinations list

这是问题:

给定Python中的项目列表,我将如何获取项目的所有可能组合?

在这个网站上有几个类似的问题,建议使用itertools.combine,但这只返回我需要的一部分:

stuff = [1, 2, 3]
for L in range(0, len(stuff)+1):
    for subset in itertools.combinations(stuff, L):
        print(subset)

()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 3)
(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

如你所见,它只返回严格顺序的项目,而不是返回(2,1),(3,2),(3,1),(2,1,3),(3,1,2),( 2,3,1)和(3,2,1).有一些解决方法吗?我似乎无法想出任何东西.

Ash*_*ary 34

用途itertools.permutations:

>>> import itertools
>>> stuff = [1, 2, 3]
>>> for L in range(0, len(stuff)+1):
        for subset in itertools.permutations(stuff, L):
                print(subset)
...         
()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
....
Run Code Online (Sandbox Code Playgroud)

帮助itertools.permutations:

permutations(iterable[, r]) --> permutations object

Return successive r-length permutations of elements in the iterable.

permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)
>>> 
Run Code Online (Sandbox Code Playgroud)


sai*_*uri 9

您可以使用这个简单的代码在python中生成列表的所有组合

import itertools

a = [1,2,3,4]
for i in xrange(1,len(a)+1):
   print list(itertools.combinations(a,i))
Run Code Online (Sandbox Code Playgroud)

结果:

[(1,), (2,), (3,), (4,)]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
[(1, 2, 3, 4)]
Run Code Online (Sandbox Code Playgroud)

  • 要求在结果中查看 (2, 1) 的问题。您的答案中的 (2, 1) 在哪里? (2认同)
  • 组合(2,1)和(1,2)都是相同的. (2认同)
  • 尽管问题中有“组合”,但它的意思是排列。读到最后,看到 (2, 1) 和 (1, 2) 都是 OP 所期望的。 (2认同)

Suk*_*lra 6

你在寻找itertools.permutations吗?

来自help(itertools.permutations),

Help on class permutations in module itertools:

class permutations(__builtin__.object)
 |  permutations(iterable[, r]) --> permutations object
 |  
 |  Return successive r-length permutations of elements in the iterable.
 |  
 |  permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)
Run Code Online (Sandbox Code Playgroud)

示例代码:

>>> from itertools import permutations
>>> stuff = [1, 2, 3]
>>> for i in range(0, len(stuff)+1):
        for subset in permutations(stuff, i):
               print(subset)


()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
Run Code Online (Sandbox Code Playgroud)

来自维基百科,排列和组合之间的区别:

排列:

非正式地,一组对象的排列是将这些对象排列成特定顺序.例如,集合{1,2,3}有六个排列,即(1,2,3),(1,3,2),(2,1,3),(2,3,1) ,(3,1,2)和(3,2,1).

组合:

在数学中,组合是一种从较大的群体中选择几种东西的方式,其中(与排列不同)顺序无关紧要.