python:逐点列表总和

max*_*max 5 python list

Input: two lists (list1, list2) of equal length
Output: one list (result) of the same length, such that:
    result[i] = list1[i] + list2[i]
Run Code Online (Sandbox Code Playgroud)

有没有简洁的方法呢?或者这是最好的:

# Python 3
assert len(list1) == len(list2)
result = [list1[i] + list2[i] for i in range(len(list1))]
Run Code Online (Sandbox Code Playgroud)

Sen*_*ran 14

您可以使用内置zip功能,也可以使用add操作符映射两个列表.像这样:

from operator import add
map(add, list1,list2)
Run Code Online (Sandbox Code Playgroud)


650*_*502 8

IMO最好的方式是

result = [x + y for x, y in zip(list1, list2)]
Run Code Online (Sandbox Code Playgroud)

与Python3基本zip甚至没有建立一个中间列表(不是一个问题,除非list1list2列表是巨大的).

但请注意,这zip将停留在输入列表中最短的位置,因此assert仍需要您.


Ign*_*ams 5

[a + b for a, b in zip(list1, list2)]
Run Code Online (Sandbox Code Playgroud)