Python 按元素查找两个列表的总和

Python 按元素查找两个列表的总和,python,list,nested,sum,Python,List,Nested,Sum,我有两个列表,我想找到两个列表元素的总和 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) 但是它给了我一个错误的结果。你可以用zip比如 >>> list1 [[1, 2, 3], [4, 5, 6]] >

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

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)

但是它给了我一个错误的结果。

你可以用
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]]
>>> import itertools
>>> y = itertools.zip_longest([1,2], [3,4,5], fillvalue=0)
>>> list(y)
[(1, 3), (2, 4), (0, 5)]
或者如果您不确定,如果两个列表的长度相同,那么您可以使用
itertools
中的
zip_longest
izip_longest
)并使用
fillvalue
类似

>>> 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]]
>>> 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]]

您可以使用numpy进行以下操作:

import numpy as np
list1=[[1, 2, 3], [4, 5, 6]]
list2=[[10, 2, 3], [11, 5, 6]]
list1_np = np.asarray(list1)
list2_np = np.asarray(list2)
total = list1_np + list2_np
print(total)
[[11 4 6]
[15 10 12]

在Python中,很少需要使用索引,特别是对于这样的任务,您希望对每个元素单独执行相同的操作。这种转换的主要功能是,列表理解提供了方便的速记。然而,
map
做的一件事是那些没有做的——像Haskell那样并行处理多个iterable。我们可以将其分为两个阶段:

list1 = [[1, 2, 3], [4, 5, 6]]
list2 = [[10, 2, 3], [11, 5, 6]]
from operator import add
def addvectors(a, b):
    return list(map(add, a, b))
list3 = list(map(addvectors, list1, list2))
在Python 2中,
map
返回一个列表,因此您不需要像我在这里使用
list
那样单独收集它