Element-wise addition of 2 lists?

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

    As described by others, a fast and also space efficient solution is using numpy (np) with it's built-in vector manipulation capability:

    1. With Numpy

    x = np.array([1,2,3])
    y = np.array([2,3,4])
    print x+y
    

    2. With built-ins

    2.1 Lambda

    list1=[1, 2, 3]
    list2=[4, 5, 6]
    print map(lambda x,y:x+y, list1, list2)
    

    Notice that map() supports multiple arguments.

    2.2 zip and list comprehension

    list1=[1, 2, 3]
    list2=[4, 5, 6]
    print [x + y for x, y in zip(list1, list2)]
    

提交回复
热议问题