计算python中的排列?

时间:2014-09-17 06:09:29

标签: python

我有一个像这样的数组:

l = [1, 4, 6, 3, 2]

对于这个数组中的每个元素,我可以“接受”它。我希望能够计算出有2 ^ n种组合时我可以采用的每种元素组合。对于这个例子,将有32种可能的安排。

例如,我可以采取: [1,4,6][3,2][1,5][1,4,6,3,2]等。

在Python中执行此操作的最佳方法是什么?这是我可以使用itertools库的问题吗?

3 个答案:

答案 0 :(得分:3)

  • itertools.permutations将返回给定长度的所有排列。
  • itertools.combinations将返回给定长度的所有组合。

您想要哪一个取决于您是否关心订购 - (1, 2)(2, 1)是不同的排列,但是相同的组合。

您可以将其与itertools.chain配对,以创建所有长度的所有排列/组合的可迭代。

from itertools import chain, permutations, combinations

# Note: if you want to include the empty combo/permutation, change the first
#       argument of the range() calls to 0.
all_length_perms = chain(permutations(l, n) for n in range(1, len(l)+1))
all_length_combos = chain(combinations(l, n) for n in range(1, len(l)+1))

# Example usage once you have the iterable...
for perm in all_length_perms:
    print(perm)

答案 1 :(得分:1)

绝对使用itertools:

 l = [1, 4, 6, 3, 2]
 for length in range(2, len(l)+1):
     for p in itertools.permutations(l, length)
         print p

有很多

答案 2 :(得分:0)

使用itertools模块

简短的难以理解的答案:

from itertools import chain, combinations
l = [1, 4, 6, 3, 2]
all_combinations = [i for i in chain(*(combinations(l, j) for j in range(len(l)+1)))]

说明:

combinations(iterable, r) --> combinations object

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

我们需要得到r = 0到len(l)+ 1的组合 我们使用链来组合每个组合