Add SUM of values of two LISTS into new LIST

2019-01-03 13:01发布

I have the following two lists:

first = [1,2,3,4,5]
second = [6,7,8,9,10]

Now I want to add items of both lists into a new list.

output should be

three = [7,9,11,13,15]

标签: python list sum
17条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-03 13:17

The zip function is useful here, used with a list comprehension.

[x + y for x, y in zip(first, second)]

If you have a list of lists (instead of just two lists):

lists_of_lists = [[1, 2, 3], [4, 5, 6]]
[sum(x) for x in zip(*lists_of_lists)]
# -> [5, 7, 9]
查看更多
我只想做你的唯一
3楼-- · 2019-01-03 13:18

Default behavior in numpy is add componentwise

import numpy as np
np.add(first, second)

which outputs

array([7,9,11,13,15])
查看更多
我命由我不由天
4楼-- · 2019-01-03 13:19

If you want to add also the rest of the values in the lists you can use this (this is working in 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))
查看更多
贼婆χ
5楼-- · 2019-01-03 13:23

Assuming both lists a and b have same length, you do not need zip, numpy or anything else.

Python 2.x and 3.x:

[a[i]+b[i] for i in range(len(a))]
查看更多
叛逆
6楼-- · 2019-01-03 13:24

This extends itself to any number of lists:

[sum(sublist) for sublist in itertools.izip(*myListOfLists)]

In your case, myListOfLists would be [first, second]

查看更多
【Aperson】
7楼-- · 2019-01-03 13:26

You can use this method but it will work only if both the list are of the same size:

first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
third = []

a = len(first)
b = int(0)
while True:
    x = first[b]
    y = second[b]
    ans = x + y
    third.append(ans)
    b = b + 1
    if b == a:
        break

print third
查看更多
登录 后发表回答