我现在有:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
我希望有:
[1, 2, 3]
+ + +
[4, 5, 6]
|| || ||
[5, 7, 9]
仅仅是两个列表的元素相加。
我当然可以迭代这两个列表,但我不想这样做。
最python化的方式是什么?
我现在有:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
我希望有:
[1, 2, 3]
+ + +
[4, 5, 6]
|| || ||
[5, 7, 9]
仅仅是两个列表的元素相加。
我当然可以迭代这两个列表,但我不想这样做。
最python化的方式是什么?
当前回答
使用numpy.add()就很简单了
import numpy
list1 = numpy.array([1, 2, 3])
list2 = numpy.array([4, 5, 6])
result = numpy.add(list1, list2) # result receive element-wise addition of list1 and list2
print(result)
array([5, 7, 9])
请参阅这里的医生
如果你想接收一个python列表:
result.tolist()
其他回答
如果您需要处理不同大小的列表,不用担心!很棒的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。
参见相关回答,并对另一个问题进行评论。
我还没有计时,但我怀疑这将是相当快的:
import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]
list_sum = (np.add(list1, list2)).tolist()
[5, 7, 9]
在我看来,使用numpy更简单:
import numpy as np
list1=[1,2,3]
list2=[4,5,6]
np.add(list1,list2)
结果:
有关详细参数信息,请查看这里:numpy.add
正如其他人所描述的那样,一个快速且节省空间的解决方案是使用numpy (np)及其内置的矢量操作功能:
1. 与Numpy
x = np.array([1,2,3])
y = np.array([2,3,4])
print x+y
2. 与整体功能
2.1λ
list1=[1, 2, 3]
list2=[4, 5, 6]
print map(lambda x,y:x+y, list1, list2)
注意map()支持多个参数。
2.2 zip和列表理解
list1=[1, 2, 3]
list2=[4, 5, 6]
print [x + y for x, y in zip(list1, list2)]
使用map与lambda函数:
>>> map(lambda x, y: x + y, list1, list2)
[5, 7, 9]