在 Python 中添加列表元素

Adding elements of lists in Python

如何将两个列表的元素相加,以创建具有更新值的新列表。例如:

a = [1,2,3]
b = [3,4,5]

answer = [4,6,8]

我知道这是一个简单的问题,但我是新手,在其他地方找不到答案...

您可以使用 itertools.izip_longest 方法来帮助解决这个问题:

def pairwise_sum(a, b):
  for x, y in itertools.izip_longest(a, b, fillvalue=0):
    yield x + y

然后你可以像这样使用它:

a = [1, 2, 3]
b = [3, 4, 5]
answer = list(pairwise_sum(a, b))

zip() 方法可能是按顺序添加列的最佳方法。

a = [1, 3, 5] #your two starting lists
b = [2, 4, 6]
c = [] #the list you would print to
for x,y in zip(a, b): #zip takes 2 iterables; x and y are placeholders for them.
    c.append(x + y) # adding on the the list

print c #final result

您可能想了解列表推导,但对于此任务而言,这不是必需的。

>>> a = [1,2,3]
>>> b = [3,4,5]
>>> map(sum, zip(a, b))
[4, 6, 8]
>>> a = [1,2,3]
>>> b = [3,4,5]
>>> import operator
>>> map(operator.add, a, b)
[4, 6, 8]

对于Python3,您需要将listmap

的结果一起使用
>>> list(map(operator.add, a, b))
[4, 6, 8]

或者只使用通常的列表理解

>>> [sum(x) for x in zip(a,b)]
[4, 6, 8]