Element-wise addition of 2 lists?

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

    Perhaps "the most pythonic way" should include handling the case where list1 and list2 are not the same size. Applying some of these methods will quietly give you an answer. The numpy approach will let you know, most likely with a ValueError.

    Example:

    import numpy as np
    >>> list1 = [ 1, 2 ]
    >>> list2 = [ 1, 2, 3]
    >>> list3 = [ 1 ]
    >>> [a + b for a, b in zip(list1, list2)]
    [2, 4]
    >>> [a + b for a, b in zip(list1, list3)]
    [2]
    >>> a = np.array (list1)
    >>> b = np.array (list2)
    >>> a+b
    Traceback (most recent call last):
      File "", line 1, in 
    ValueError: operands could not be broadcast together with shapes (2) (3)
    

    Which result might you want if this were in a function in your problem?

提交回复
热议问题