Answers:
此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,则将可迭代对象压缩的结果将为长度
>>> lists_of_lists = [[1, 2, 3], [4, 5, 6]]
>>> [sum(x) for x in zip(*lists_of_lists)]
[5, 7, 9]
numpy中的默认行为是逐组件添加
import numpy as np
np.add(first, second)
哪个输出
array([7,9,11,13,15])
这可以扩展到任意数量的列表:
[sum(sublist) for sublist in itertools.izip(*myListOfLists)]
在你的情况下,myListOfLists
将[first, second]
izip.from_iterable
吗?
chain
。更新
尝试以下代码:
first = [1, 2, 3, 4]
second = [2, 3, 4, 5]
third = map(sum, zip(first, second))
map(sum, zip(first, second, third, fourth, ...))
执行此操作的简单方法和快速方法是:
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])
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]
Thiru在3月17日9:25回答了我的问题。
这更加简单快捷,这是他的解决方案:
执行此操作的简单方法和快速方法是:
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])
您需要numpy!
numpy数组可以做一些像矢量的操作import numpy as np
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = list(np.array(a) + np.array(b))
print c
# [7, 9, 11, 13, 15]
这是另一种方法。我们利用python的内部__add__函数:
class SumList(object):
def __init__(self, this_list):
self.mylist = this_list
def __add__(self, other):
new_list = []
zipped_list = zip(self.mylist, other.mylist)
for item in zipped_list:
new_list.append(item[0] + item[1])
return SumList(new_list)
def __repr__(self):
return str(self.mylist)
list1 = SumList([1,2,3,4,5])
list2 = SumList([10,20,30,40,50])
sum_list1_list2 = list1 + list2
print(sum_list1_list2)
输出量
[11, 22, 33, 44, 55]
如果您还想添加列表中的其余值,则可以使用它(在Python3.5中有效)
def addVectors(v1, v2):
sum = [x + y for x, y in zip(v1, v2)]
if not len(v1) >= len(v2):
sum += v2[len(v1):]
else:
sum += v1[len(v2):]
return sum
#for testing
if __name__=='__main__':
a = [1, 2]
b = [1, 2, 3, 4]
print(a)
print(b)
print(addVectors(a,b))
first = [1,2,3,4,5]
second = [6,7,8,9,10]
#one way
third = [x + y for x, y in zip(first, second)]
print("third" , third)
#otherway
fourth = []
for i,j in zip(first,second):
global fourth
fourth.append(i + j)
print("fourth" , fourth )
#third [7, 9, 11, 13, 15]
#fourth [7, 9, 11, 13, 15]
这是另一种方法。它对我来说很好。
N=int(input())
num1 = list(map(int, input().split()))
num2 = list(map(int, input().split()))
sum=[]
for i in range(0,N):
sum.append(num1[i]+num2[i])
for element in sum:
print(element, end=" ")
print("")
j = min(len(l1), len(l2))
l3 = [l1[i]+l2[i] for i in range(j)]
也许是最简单的方法:
first = [1,2,3,4,5]
second = [6,7,8,9,10]
three=[]
for i in range(0,5):
three.append(first[i]+second[i])
print(three)