Element-wise addition of two list of different lengths?

前端 未结 3 611
面向向阳花
面向向阳花 2021-01-26 20:30

How to perform element-wise addition of different length lists?
Assuming \"0\" for missing elements.
Note: len(a) will always be less than or equal to len(b)

exa

3条回答
  •  渐次进展
    2021-01-26 21:31

    you can pad a with zeroes like this and use sum

    a=[1,2,3]
    b=[1,2,3,4,5]
    a[:] = [a[i] if i < len(a) else 0 for i,j in enumerate(b)]
    result=[sum(n) for n in zip(a,b)]
    print result
    

    results in

    [2, 4, 6, 4, 5]
    

提交回复
热议问题