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)
IMO最好的方式是
result = [x + y for x, y in zip(list1, list2)]
Run Code Online (Sandbox Code Playgroud)
与Python3基本zip
甚至没有建立一个中间列表(不是一个问题,除非list1
和list2
列表是巨大的).
但请注意,这zip
将停留在输入列表中最短的位置,因此assert
仍需要您.