我现在有:

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

我希望有:

[1, 2, 3]
 +  +  +
[4, 5, 6]
|| || ||
[5, 7, 9]

仅仅是两个列表的元素相加。

我当然可以迭代这两个列表,但我不想这样做。

最python化的方式是什么?


当前回答

使用map与lambda函数:

>>> map(lambda x, y: x + y, list1, list2)
[5, 7, 9]

其他回答

[list1[i] + list2[i] for i in range(len(list1))]

在我看来,使用numpy更简单:

import numpy as np
list1=[1,2,3]
list2=[4,5,6]
np.add(list1,list2)

结果:

有关详细参数信息,请查看这里:numpy.add

a_list = []
b_list = []
for i in range(1,100):
    a_list.append(random.randint(1,100))

for i in range(1,100):
    a_list.append(random.randint(101,200))
[sum(x) for x in zip(a_list , b_list )]

这将适用于2个或更多的列表;遍历列表的列表,但使用numpy加法处理每个列表的元素

import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]

lists = [list1, list2]
list_sum = np.zeros(len(list1))
for i in lists:
   list_sum += i
list_sum = list_sum.tolist()    

[5.0, 7.0, 9.0]

如果您需要处理不同大小的列表,不用担心!很棒的itertools模块已经介绍过了:

>>> from itertools import zip_longest
>>> list1 = [1,2,1]
>>> list2 = [2,1,2,3]
>>> [sum(x) for x in zip_longest(list1, list2, fillvalue=0)]
[3, 3, 3, 3]
>>>

在Python 2中,zip_longest被称为izip_longest。

参见相关回答,并对另一个问题进行评论。