我现在有:

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

我希望有:

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

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

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

最python化的方式是什么?


当前回答

正如其他人所描述的那样,一个快速且节省空间的解决方案是使用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]

也许“最python化的方式”应该包括处理list1和list2大小不同的情况。运用其中的一些方法,你会不动声色地得到答案。numpy方法会让您知道,很可能使用ValueError。

例子:

import numpy as np
>>> list1 = [ 1, 2 ]
>>> list2 = [ 1, 2, 3]
>>> list3 = [ 1 ]
>>> [a + b for a, b in zip(list1, list2)]
[2, 4]
>>> [a + b for a, b in zip(list1, list3)]
[2]
>>> a = np.array (list1)
>>> b = np.array (list2)
>>> a+b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (2) (3)

如果这是你问题中的函数你想要什么结果?

其他人给出了如何在纯python中做到这一点的示例。如果你想对包含100.000个元素的数组执行此操作,你应该使用numpy:

In [1]: import numpy as np
In [2]: vector1 = np.array([1, 2, 3])
In [3]: vector2 = np.array([4, 5, 6])

现在,按元素进行添加非常简单

In [4]: sum_vector = vector1 + vector2
In [5]: print sum_vector
[5 7 9]

就像Matlab一样。

与Ashwini的最快版本进行比较的时间:

In [16]: from operator import add
In [17]: n = 10**5
In [18]: vector2 = np.tile([4,5,6], n)
In [19]: vector1 = np.tile([1,2,3], n)
In [20]: list1 = [1,2,3]*n
In [21]: list2 = [4,5,6]*n
In [22]: timeit map(add, list1, list2)
10 loops, best of 3: 26.9 ms per loop

In [23]: timeit vector1 + vector2
1000 loops, best of 3: 1.06 ms per loop

所以这要快25倍!但是要用适合你的情况。对于一个简单的程序,您可能不想安装numpy,因此使用标准的python(我发现Henry的版本是最python的版本)。如果你喜欢严肃的数字运算,让numpy来做繁重的工作。对于速度狂人来说:似乎numpy解决方案在n = 8左右开始时更快。

我还没有计时,但我怀疑这将是相当快的:

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

list_sum = (np.add(list1, list2)).tolist()

[5, 7, 9]

使用map和operator.add:

>>> from operator import add
>>> list( map(add, list1, list2) )
[5, 7, 9]

或者压缩一个列表理解:

>>> [sum(x) for x in zip(list1, list2)]
[5, 7, 9]

时间比较:

>>> list2 = [4, 5, 6]*10**5
>>> list1 = [1, 2, 3]*10**5
>>> %timeit from operator import add;map(add, list1, list2)
10 loops, best of 3: 44.6 ms per loop
>>> %timeit from itertools import izip; [a + b for a, b in izip(list1, list2)]
10 loops, best of 3: 71 ms per loop
>>> %timeit [a + b for a, b in zip(list1, list2)]
10 loops, best of 3: 112 ms per loop
>>> %timeit from itertools import izip;[sum(x) for x in izip(list1, list2)]
1 loops, best of 3: 139 ms per loop
>>> %timeit [sum(x) for x in zip(list1, list2)]
1 loops, best of 3: 177 ms per loop