我有以下两个清单:
first = [1,2,3,4,5]
second = [6,7,8,9,10]
Run Code Online (Sandbox Code Playgroud)
现在我想将两个列表的项目添加到新列表中.
输出应该是
third = [7,9,11,13,15]
Run Code Online (Sandbox Code Playgroud)
tom*_*tom 185
此zip
功能在此处很有用,与列表推导一起使用.
[x + y for x, y in zip(first, second)]
Run Code Online (Sandbox Code Playgroud)
如果您有一个列表列表(而不是只有两个列表):
lists_of_lists = [[1, 2, 3], [4, 5, 6]]
[sum(x) for x in zip(*lists_of_lists)]
# -> [5, 7, 9]
Run Code Online (Sandbox Code Playgroud)
Tha*_*ran 48
来自docs
import operator
list(map(operator.add, first,second))
Run Code Online (Sandbox Code Playgroud)
mat*_*ath 27
假设两个列表a
,并b
具有相同的长度,你不需要压缩,numpy的或其他任何东西.
Python 2.x和3.x:
[a[i]+b[i] for i in range(len(a))]
Run Code Online (Sandbox Code Playgroud)
小智 20
numpy中的默认行为是按分数添加
import numpy as np
np.add(first, second)
Run Code Online (Sandbox Code Playgroud)
哪个输出
array([7,9,11,13,15])
Run Code Online (Sandbox Code Playgroud)
ins*_*get 11
这扩展到任意数量的列表:
[sum(sublist) for sublist in itertools.izip(*myListOfLists)]
Run Code Online (Sandbox Code Playgroud)
在你的情况下,myListOfLists
将是[first, second]
小智 9
请尝试以下代码:
first = [1, 2, 3, 4]
second = [2, 3, 4, 5]
third = map(sum, zip(first, second))
Run Code Online (Sandbox Code Playgroud)
简单的方法和快速的方法是:
three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]
Run Code Online (Sandbox Code Playgroud)
或者,你可以使用numpy sum:
from numpy import sum
three = sum([first,second], axis=0) # array([7,9,11,13,15])
Run Code Online (Sandbox Code Playgroud)
first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
three = map(lambda x,y: x+y,first,second)
print three
Output
[7, 9, 11, 13, 15]
Run Code Online (Sandbox Code Playgroud)