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:08

Try the following code:

first = [1, 2, 3, 4]
second = [2, 3, 4, 5]
third = map(sum, zip(first, second))
查看更多
欢心
3楼-- · 2019-01-03 13:10

From docs

import operator
map(operator.add, first,second)
查看更多
贪生不怕死
4楼-- · 2019-01-03 13:13

Here is another way to do it.It is working fine for me .

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("")
查看更多
ら.Afraid
5楼-- · 2019-01-03 13:15

The easy way and fast way to do this is:

three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]

Alternatively, you can use numpy sum:

from numpy import sum
three = sum([first,second], axis=0) # array([7,9,11,13,15])
查看更多
We Are One
6楼-- · 2019-01-03 13:15
    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]
查看更多
小情绪 Triste *
7楼-- · 2019-01-03 13:15

Perhaps the simplest approach:

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)
查看更多
登录 后发表回答