首页 > 解决方案 > 按元素查找两个列表列表的总和

问题描述

我有两个列表列表,我想从两个列表元素中找到总和

list1 = [[1, 2, 3], [4, 5, 6]]
list2 = [[10, 2, 3], [11, 5, 6]]

结果应该是[11, 4, 6], [15, 10, 12]
目前,我有

for i in len(list1):
    sum = list1[i] + list2[i]
print(sum)

但它给了我错误的结果。

标签: pythonlistnestedsum

解决方案


你可以zip像这样使用,

>>> list1
[[1, 2, 3], [4, 5, 6]]
>>> list2
[[10, 2, 3], [11, 5, 6]]
>>> [[x+y for x,y in zip(l1, l2)] for l1,l2 in zip(list1,list2)]
[[11, 4, 6], [15, 10, 12]]

或者如果您不确定,如果两个列表的长度相同,那么您可以使用zip_longestizip_longest在 python2 中) fromitertools和使用fillvalue类似的,

>>> import itertools
>>> y = itertools.zip_longest([1,2], [3,4,5], fillvalue=0)
>>> list(y)
[(1, 3), (2, 4), (0, 5)]

然后您可以将其用于大小不等的数据,例如,

>>> from itertools import zip_longest
>>> list1=[[1, 2, 3], [4, 5]]
>>> list2=[[10, 2, 3], [11, 5, 6], [1,2,3]]
>>> [[x+y for x,y in zip_longest(l1, l2, fillvalue=0)] for l1,l2 in zip_longest(list1,list2, fillvalue=[])]
[[11, 4, 6], [15, 10, 6], [1, 2, 3]]

推荐阅读