问题描述
有没有办法返回整数列表的各种和?还是Pythonic。
例如[1,2,3,4]
的各种总计将产生1+2=3,1+3=4,1+4=5,2+3=5,2+4=6,3+4=7
。默认情况下,要求和的整数只能固定为两个整数或更多,我猜。
似乎无法全神贯注于如何解决此问题,并且似乎无法在互联网上找到示例或解释,因为它们都会导致“列表中的奇数/奇数加总”和其他不同的问题。 / p>
解决方法
您可以使用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,3) 6
(1,4) 8
(2,4) 9
,
这是您要寻找的吗?
A=[1,4] for i in A: for j in A: if i!=j: print(i+j)