首页 > 解决方案 > 返回整数列表的各种总和

问题描述

有没有办法返回整数列表的各种总和?Pythonic 或其他。

例如,来自的各种总和[1, 2, 3, 4]将产生1+2=3, 1+3=4, 1+4=5, 2+3=5, 2+4=6, 3+4=7。我猜默认情况下,要求和的整数只能被固定在两个整数或更多整数上。

似乎无法解决如何解决这个问题,并且似乎无法在互联网上找到示例或解释,因为它们都会导致“列表中的偶数/奇数相加”和其他不同的问题。

标签: pythonlistsum

解决方案


您可以使用itertools.combinationssum

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

推荐阅读