python - 返回整数列表的各种总和
问题描述
有没有办法返回整数列表的各种总和?Pythonic 或其他。
例如,来自的各种总和[1, 2, 3, 4]
将产生1+2=3, 1+3=4, 1+4=5, 2+3=5, 2+4=6, 3+4=7
。我猜默认情况下,要求和的整数只能被固定在两个整数或更多整数上。
似乎无法解决如何解决这个问题,并且似乎无法在互联网上找到示例或解释,因为它们都会导致“列表中的偶数/奇数相加”和其他不同的问题。
解决方案
您可以使用itertools.combinations
和sum
:
from itertools import combinations
li = [1, 2, 3, 4]
# assuming we don't need to sum the entire list or single numbers,
# and that x + y is the same as y + x
for sum_size in range(2, len(li)):
for comb in combinations(li, sum_size):
print(comb, sum(comb))
输出
(1, 2) 3
(1, 3) 4
(1, 4) 5
(2, 3) 5
(2, 4) 6
(3, 4) 7
(1, 2, 3) 6
(1, 2, 4) 7
(1, 3, 4) 8
(2, 3, 4) 9
推荐阅读
- angular - 处理Angular中的浏览器刷新按钮
- css - 为什么 % 的最高值在 Google chrome 中没有响应,而在 Firefox 中却没有响应?
- python - Python,Pyinstaller,图像,声音
- powershell - 需要使用 powershell 选择“正确”的驱动程序
- node.js - 安装nodemon的问题
- r - 在 R 中使用环境和 ggplot2 进行故障排除
- c - 访问大型堆数组时出现分段错误(核心转储)
- algorithm - 使用主定理方法求解递归 T(n) = T(n / 2) - T(n / 6) + O(lg n)?
- javascript - 如何在javascript中获得曲线的边界框
- ffmpeg - 使用 ffmpeg 分析来自 Wirecast 的单播流