我有以下两个列表:
first = [1,2,3,4,5]
second = [6,7,8,9,10]
现在我想将这两个列表中的项目添加到一个新列表中。
输出应该是
third = [7,9,11,13,15]
zip
函数在这里非常有用,可以与列表推导一起使用。
[x + y for x, y in zip(first, second)]
如果您有一个列表的列表(而不仅是两个列表):lists_of_lists = [[1, 2, 3], [4, 5, 6]]
[sum(x) for x in zip(*lists_of_lists)]
# -> [5, 7, 9]
first
长度为10,而second
长度为6,则将这两个可迭代对象进行压缩操作的结果长度为6。 - tom>>> lists_of_lists = [[1, 2, 3], [4, 5, 6]]
>>> [sum(x) for x in zip(*lists_of_lists)]
[5, 7, 9]
- tom来自文档
import operator
list(map(operator.add, first,second))
numpy.add
(numpy.subtract
等)的默认行为是逐元素进行操作:
import numpy as np
np.add(first, second)
输出
array([7,9,11,13,15])
假设列表 a
和 b
长度相同,则不需要使用zip、numpy或任何其他工具。
Python 2.x和3.x:
[a[i]+b[i] for i in range(len(a))]
尝试以下代码:
first = [1, 2, 3, 4]
second = [2, 3, 4, 5]
third = map(sum, zip(first, second))
map(sum, zip(first, second, third, fourth, ...))
- Johan Dettmar这适用于任意数量的列表:
[sum(sublist) for sublist in itertools.izip(*myListOfLists)]
在你的情况下,myListOfLists
将是 [first, second]
izip.from_iterable
吗? - DSMfirst = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
three = list(map(sum, first, second))
print(three)
# Output
[7, 9, 11, 13, 15]
lambda x, y: x + y
可以简单地写成 sum
。 - ggorlen完成这个任务的简单快捷方法是:
three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]
或者,您可以使用numpy sum:
from numpy import sum
three = sum([first,second], axis=0) # array([7,9,11,13,15])
一行解决方案
list(map(lambda x,y: x+y, a,b))
def sum_lists(*args):
return list(map(sum, zip(*args)))
a = [1,2,3]
b = [1,2,3]
sum_lists(a,b)
输出:
[2, 4, 6]
或者使用3个列表
sum_lists([5,5,5,5,5], [10,10,10,10,10], [4,4,4,4,4])
输出:
[19, 19, 19, 19, 19]