简体   繁体   中英

Adding elements of lists in Python

How can I add up the elements of two lists in order to make a new list with the updated values. For example:

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

answer = [4,6,8]

I know this is a simple question, but I am new to this thing and cant find an answer anywhere else...

The zip() method would probably be the best way to add up columns, in that order.

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

You may want to learn about list comprehensions, but for this task, it is not required.

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

For Python3, you need to use list with the result of map

>>> list(map(operator.add, a, b))
[4, 6, 8]

or just use the usual list comprehension

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

You can use the itertools.izip_longest method to help with this:

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

You can then use it like this:

a = [1, 2, 3]
b = [3, 4, 5]
answer = list(pairwise_sum(a, b))
>>> a = [1,2,3]
>>> b = [3,4,5]
>>> map(sum, zip(a, b))
[4, 6, 8]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM