繁体   English   中英

在Python中生成排列的子集,但不是所有排列

[英]Generating subsets of a permutation in Python but not all permutations

我有一个列表L = [1,2,3] ,我想计算所有组合的乘积,但仅一次-即:

null # that is, no elements of the list are multiplied
1
2
3
1 * 2
1 * 3
2 * 3
1 * 2 * 3

我看过很多关于使用itertools ,排列和组合的文章,但是这些返回结果包括[1,2,3][2,1,3][3,2,1]等,这是不是我追求的。 (如果知道这一点,我正在使用Python 3)

NB非常了解,这可能是我搜索技能的失败,而且我只是不知道我要寻找的确切术语。

您想要的只是所有子集。 事实证明, itertools配方提供了一种生成可迭代对象幂集的灵巧方法。

from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

from functools import reduce
from operator import mul

for values in powerset([1, 2, 3]):
    print(' * '.join([str(x) for x in values]),
          '=',
          reduce(mul, values, 1))

产量

 = 1
1 = 1
2 = 2
3 = 3
1 * 2 = 2
1 * 3 = 3
2 * 3 = 6
1 * 2 * 3 = 6

您需要集合的集。 itertools有一个如何找到它的示例。

https://docs.python.org/2/library/itertools.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM