Element-wise addition of 2 lists?

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

    If you need to handle lists of different sizes, worry not! The wonderful itertools module has you covered:

    >>> from itertools import zip_longest
    >>> list1 = [1,2,1]
    >>> list2 = [2,1,2,3]
    >>> [sum(x) for x in zip_longest(list1, list2, fillvalue=0)]
    [3, 3, 3, 3]
    >>>
    

    In Python 2, zip_longest is called izip_longest.

    See also this relevant answer and comment on another question.

提交回复
热议问题