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

You can use zip(), which will "interleave" the two arrays together, and then map(), which will apply a function to each element in an iterable:

>>> a = [1,2,3,4,5]
>>> b = [6,7,8,9,10]
>>> zip(a, b)
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
>>> map(lambda x: x[0] + x[1], zip(a, b))
[7, 9, 11, 13, 15]
查看更多
够拽才男人
3楼-- · 2019-01-03 13:29

Here is another way to do it. We make use of the internal __add__ function of python:

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)

Output

[11, 22, 33, 44, 55]
查看更多
贪生不怕死
4楼-- · 2019-01-03 13:29

My answer is repeated with Thiru's that answered it in Mar 17 at 9:25.

It was simpler and quicker, here are his solutions:

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])

You need numpy!

numpy array could do some operation like vectors

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]
查看更多
小情绪 Triste *
5楼-- · 2019-01-03 13:30
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]
查看更多
等我变得足够好
6楼-- · 2019-01-03 13:33
j = min(len(l1), len(l2))
l3 = [l1[i]+l2[i] for i in range(j)]
查看更多
登录 后发表回答