Element-wise addition of two list of different lengths?

前端 未结 3 496
面向向阳花
面向向阳花 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:17

    There's an alternative zip that does not stop at the shortest: itertools.zip_longest(). You can specify a fill value for the shorter lists:

    from itertools import zip_longest
    
    result = [sum(n) for n in zip_longest(a, b, fillvalue=0)]
    

提交回复
热议问题