2016-12-24 102 views
-5

我定义2所列出,N1和N2:如何通过一次性添加2个列表元素在python中形成一个新列表?

In [1]: n1=[1,2,3] 

In [2]: n2=[4,5,6] 

In [3]: n1+n2 
Out[3]: [1, 2, 3, 4, 5, 6] 

In [4]: n1+=n2 

In [5]: n1 
Out[5]: [1, 2, 3, 4, 5, 6] 

那么,我希望做的是得到一个新的列表: N3 = [5,7,9]作为每个元素的汇总n1和n2。

我不想写一个for循环来完成这个例行工作。 Python操作符或库是否支持一次性调用来执行此操作?

+3

参见[这里] (http://stackoverflow.com/questions/18713321/element-wise-addition-of-2-lists-in-python),[here](http://stackoverflow.com/questions/8451 12/concise-vector-in-python),[here](http://stackoverflow.com/questions/14050824/add-sum-of-values-of-two-lists-into-new-list),可能还有更多。 – TigerhawkT3

回答

1
[x + y for x, y in zip(n1, n2)] 
[n1[i] + n2[i] for i in range(len(n1))] 
map(int.__add__, n1, n2) 
+0

这个人很棒。 – Troskyvs

0

不,这里没有一次性命令。在两个列表中添加元素不是常见操作。这里你不能避免循环。

使用zip()list comprehension

[a + b for a, b in zip(n1, n2)] 

另外,使用numpy数组:

from numpy import array 

n3 = array(n1) + array(n2) 
1

我不想写一个for循环做这个工作程序。 python操作员或库是否支持一次性调用来执行此操作?

Python不支持它本身,但是你可以使用这个库NumPy

import numpy as np 

n1 = np.array([1, 2, 3]) 
n2 = np.array([4, 5, 6]) 

n3 = n1 + n2 

或者,你可以使用list comprehensionzip()

n3 = [x + y for x, y in zip(n1, n2)] 
相关问题