Python,一个带有索引组合的简单总和列表

标签 python list

我有以下列表

Values=[ 0 , 1 , 2 ]

我的目标是产生以下内容

MySums=[1+2,0+2,0+1]

是否有组合的内置函数?

最佳答案

是的,您可以使用 itertools.combinations

import itertools

In [6]: values = [0, 1, 2]

In [7]: list(itertools.combinations(values, 2))
Out[7]: [(0, 1), (0, 2), (1, 2)]

如果你想对它们求和:

In [9]: list(sum(x) for x in itertools.combinations(values, 2))
Out[9]: [1, 2, 3]

关于Python,一个带有索引组合的简单总和列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16297309/

相关文章:

python - 如何从字符串中获取 mongodb 的有效对象 ID?

python - Celery 如何处理链内的任务失败?

c - 通过 C 中的标准输入读取大型列表

performance - 使我的 List.filter 在 Scala 上更快?

python : Print list of list as tables

python - 我可以在 VBA 中使用我的 python 自定义对象吗?

python - 基于索引的输出行

python - 解包 : [x, y], (x,y), x,y - 有什么区别?

python - 在 Python 中删除和替换多项式的系数

python - 如何在 python 列表中添加 kg 或 grams 'superficially ' 等单位