Element-wise addition of 2 lists?

后端 未结 16 1180
感动是毒
感动是毒 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:43

    This will work for 2 or more lists; iterating through the list of lists, but using numpy addition to deal with elements of each list

    import numpy as np
    list1=[1, 2, 3]
    list2=[4, 5, 6]
    
    lists = [list1, list2]
    list_sum = np.zeros(len(list1))
    for i in lists:
       list_sum += i
    list_sum = list_sum.tolist()    
    
    [5.0, 7.0, 9.0]
    

提交回复
热议问题