简体   繁体   English

列表中每个元素的总和

[英]Sum of every element in a list

So i have a list:所以我有一个清单:

list1 = [[1, 3, 6, 8, 9, 9, 12], [1, 2, 3, 2, 1, 0, 3, 3]]

but you can also split it into two lists, if it make it any easier.但你也可以把它分成两个列表,如果它更容易的话。 All i have to do is sum every digit with every other digit.我所要做的就是将每个数字与其他数字相加。 Like you know first row:就像你知道的第一行:

1+1, 1+2, 1+3, 1+2, 1+1... 1+1、1+2、1+3、1+2、1+1...

second:第二:

3+1... etc. 3+1...等

first = [1, 3, 6, 8, 9, 9, 12]
second = [1, 2, 3, 2, 1, 0, 3, 3]

w = [x + y for x, y in zip(first, second)]

I was trying to do it in this way.我试图以这种方式做到这一点。 But it doesn't work*, any ideas?但它不起作用*,有什么想法吗?

*i mean its summing in a wrong way, instead of every possible digits with every possible, just the first one in 1st list with 1st in second list. *我的意思是它以错误的方式求和,而不是所有可能的数字,只是第一个列表中的第一个和第二个列表中的第一个。

zip is getting only pairs that sit at the same index. zip仅获得位于同一索引处的对。 You should instead have a double loop:你应该有一个双循环:

[x + y for x in first for y in second]

You can do it using itertools to get all possible pair then make a pair of sum list您可以使用itertools来获取所有可能的对,然后制作一对总和列表

import itertools
first = [1, 3, 6, 8, 9, 9, 12]
second = [1, 2, 3, 2, 1, 0, 3, 3]

res = itertools.product(first, second)
ress = [sum(pair) for pair in res]
print(ress)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM