Add two arrays without using for. Python

前端 未结 4 1070
后悔当初
后悔当初 2021-01-17 06:26

I have these two arrays:

import numpy as np
a = np.array([0, 10, 20])
b = np.array([20, 30, 40, 50])  

I´d like to add both in the followin

4条回答
  •  伪装坚强ぢ
    2021-01-17 07:19

    Here you go:

    In [17]: a = np.array([0, 10, 20])
    
    In [18]: b = np.array([20, 30, 40, 50])  
    
    In [19]: (a.reshape(-1, 1) + b).ravel()
    Out[19]: array([20, 30, 40, 50, 30, 40, 50, 60, 40, 50, 60, 70])
    

    Here are the details.

    a.reshape(-1, 1) converts a to an array with shape (3, 1):

    In [20]: a.reshape(-1, 1)
    Out[20]: 
    array([[ 0],
           [10],
           [20]])
    

    When b is added to that, broadcasting applies, which in effect does an "outer sum" (i.e. adds all the pairwise combinations), forming an array with shape (3, 4):

    In [21]: a.reshape(-1, 1) + b
    Out[21]: 
    array([[20, 30, 40, 50],
           [30, 40, 50, 60],
           [40, 50, 60, 70]])
    

    The ravel() method flattens the result into a one-dimensional array:

    In [22]: (a.reshape(-1, 1) + b).ravel()
    Out[22]: array([20, 30, 40, 50, 30, 40, 50, 60, 40, 50, 60, 70])
    

    See @HYRY's answer for an even more concise version.

提交回复
热议问题