Python 按元素添加 2 个列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18713321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Element-wise addition of 2 lists?
提问by Sibbs Gambling
I have now:
我现在有了:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
I wish to have:
我希望有:
[1, 2, 3]
+ + +
[4, 5, 6]
|| || ||
[5, 7, 9]
Simply an element-wise addition of two lists.
简单地将两个列表按元素相加。
I can surely iterate the two lists, but I don't want do that.
我当然可以迭代这两个列表,但我不想这样做。
What is the most Pythonic wayof doing so?
什么是最Python的方式这样做的?
采纳答案by Ashwini Chaudhary
Use map
with operator.add
:
使用map
有operator.add
:
>>> from operator import add
>>> list( map(add, list1, list2) )
[5, 7, 9]
or zip
with a list comprehension:
或zip
使用列表理解:
>>> [sum(x) for x in zip(list1, list2)]
[5, 7, 9]
Timing comparisons:
时序比较:
>>> 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
回答by Henry Gomersall
[a + b for a, b in zip(list1, list2)]
回答by Bas Swinckels
The others gave examples how to do this in pure python. If you want to do this with arrays with 100.000 elements, you should use numpy:
其他人给出了如何在纯 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])
Doing the element-wise addition is now as trivial as
进行逐元素加法现在就像
In [4]: sum_vector = vector1 + vector2
In [5]: print sum_vector
[5 7 9]
just like in Matlab.
就像在 Matlab 中一样。
Timing to compare with Ashwini's fastest version:
与 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
So this is a factor 25 faster! But use what suits your situation. For a simple program, you probably don't want to install numpy, so use standard python (and I find Henry's versionthe most Pythonic one). If you are into serious number crunching, let numpy
do the heavy lifting. For the speed freaks: it seems that the numpy solution is faster starting around n = 8
.
所以这快了 25 倍!但是使用适合您情况的方法。对于一个简单的程序,你可能不想安装 numpy,所以使用标准的 python(我发现Henry 的版本是最 Pythonic的版本)。如果您正在处理大量的数字运算,那么让我们numpy
来做繁重的工作吧。对于速度怪胎:似乎 numpy 解决方案从n = 8
.
回答by Fred Mitchell
Perhaps "the most pythonic way" should include handling the case where list1 and list2 are not the same size. Applying some of these methods will quietly give you an answer. The numpy approach will let you know, most likely with a ValueError.
也许“最 Pythonic 的方式”应该包括处理 list1 和 list2 大小不同的情况。应用其中一些方法会悄悄地给你一个答案。numpy 方法会让您知道,最有可能是 ValueError。
Example:
例子:
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)
Which result might you want if this were in a function in your problem?
如果这在您的问题中的函数中,您可能想要哪个结果?
回答by Peaters
Use map with lambda function:
将 map 与 lambda 函数一起使用:
>>> map(lambda x, y: x + y, list1, list2)
[5, 7, 9]
回答by litepresence
I haven't timed it but I suspect this would be pretty quick:
我没有计时,但我怀疑这会很快:
import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]
list_sum = (np.add(list1, list2)).tolist()
[5, 7, 9]
回答by litepresence
This will work for 2 or more lists; iterating through the list of lists, but using numpy addition to deal with elements of each 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]
回答by wgr
[list1[i] + list2[i] for i in range(len(list1))]
回答by jjst
If you need to handle lists of different sizes, worry not! The wonderful itertoolsmodule has you covered:
如果您需要处理不同大小的列表,请不要担心!精彩的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]
>>>
In Python 2, zip_longest
is called izip_longest
.
在 Python 2 中,zip_longest
称为izip_longest
.
See also this relevant answer and comment on another question.
另请参阅此相关答案并评论另一个问题。
回答by MasterControlProgram
As described by others, a fast and also space efficient solution is using numpy (np) with it's built-in vector manipulation capability:
正如其他人所描述的,一个快速且节省空间的解决方案是使用 numpy (np) 及其内置的向量操作功能:
1. With Numpy
1. 使用 Numpy
x = np.array([1,2,3])
y = np.array([2,3,4])
print x+y
2. With built-ins
2. 内置插件
2.1 Lambda
2.1 拉姆达
list1=[1, 2, 3]
list2=[4, 5, 6]
print map(lambda x,y:x+y, list1, list2)
Notice that map() supports multiple arguments.
请注意 map() 支持多个参数。
2.2 zip and list comprehension
2.2 zip 和列表理解
list1=[1, 2, 3]
list2=[4, 5, 6]
print [x + y for x, y in zip(list1, list2)]