python: pointwise list sum

六眼飞鱼酱① 提交于 2021-02-18 11:50:42

问题


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

Is there any concise way to do that? Or is this the best:

# Python 3
assert len(list1) == len(list2)
result = [list1[i] + list2[i] for i in range(len(list1))]

回答1:


You can use the builtin zip function, or you can also use do it mapping the two lists over the add operator. Like this:

from operator import add
map(add, list1,list2)



回答2:


IMO the nicest way is

result = [x + y for x, y in zip(list1, list2)]

with Python3 basic zip is not even building an intermediate list (not an issue unless list1 and list2 lists are huge).

Note however that zip will stop at the shortest of the input lists, so your assert is still needed.




回答3:


[a + b for a, b in zip(list1, list2)]



回答4:


There are several ways, e.g. using map, sum and izip (but afaik, zip works the same as izip in Python 3):

>>> from itertools import izip
>>> map(sum, izip(list1, list2))



回答5:


I'd do:

result = [x+x for x,y in zip(list1, list2)]


来源:https://stackoverflow.com/questions/5788470/python-pointwise-list-sum

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!