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

标签 python

我有一个列表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 recipes提供了一种简洁的方法来生成可迭代的幂集

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

关于python - 在Python中生成排列的子集但不是所有排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51987139/

相关文章:

python - bash 运行 python 脚本时出现语法错误

python - 如何在pygame中更改一段文本的颜色

python - Django - 在管理模板中保存我的对象后执行函数

python - 值错误: too many values to unpack (expected 3) using PIL

python - CherryPy - 使用直接下载还是我的发行版?

python - 比较两个数据帧的列并创建一个新数据帧

python - os.path.dirname(__file__) 返回空

python - 我怎样才能用这样的高斯函数做更好的曲线拟合?

Python 处理 TypeError :

python - 如何使用 pyodbc 获取 SQL Server 存储过程的返回值?