Element-wise addition of 2 lists?

后端 未结 16 1544
感动是毒
感动是毒 2020-11-22 07:48

I have now:

list1 = [1, 2, 3]
list2 = [4, 5, 6]

I wish to have:

[1, 2, 3]
 +  +  +         


        
16条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 08:22

    Perhaps this is pythonic and slightly useful if you have an unknown number of lists, and without importing anything.

    As long as the lists are of the same length, you can use the below function.

    Here the *args accepts a variable number of list arguments (but only sums the same number of elements in each).

    The * is used again in the returned list to unpack the elements in each of the lists.

    def sum_lists(*args):
        return list(map(sum, zip(*args)))
    
    a = [1,2,3]
    b = [1,2,3]  
    
    sum_lists(a,b)
    

    Output:

    [2, 4, 6]
    

    Or with 3 lists

    sum_lists([5,5,5,5,5], [10,10,10,10,10], [4,4,4,4,4])
    

    Output:

    [19, 19, 19, 19, 19]
    

提交回复
热议问题