如何在python中一次将2个列表元素相加形成一个新列表?

How to add up 2 list elements to form a new list in python, by one shot?

我定义了 2 个列表,n1 和 n2:

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 运算符或库是否支持一次性调用来执行此操作?

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

使用zip() and a list comprehension:

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

或者,使用 numpy 数组:

from numpy import array

n3 = array(n1) + array(n2)

I don't wish to write a for loop to do this routine job. Does python operator or library support a one-shot call to do this?

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

import numpy as np

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

n3 = n1 + n2

或者,您可以使用 list comprehension and zip():

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