Add two arrays without using for. Python

前端 未结 4 1108
后悔当初
后悔当初 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:07

    One possible and only memory not time intensive solution is using np.repeat and np.resize to repeat and resize the arrays a and b to the size of the resulting shape first and then simply add those two arrays.

    Code:

    import numpy as np
    a = np.array([0, 10, 20])
    b = np.array([20, 30, 40, 50])
    
    def extend_and_add(a, b):
        return np.repeat(a, len(b)) + np.resize(b, len(a)*len(b))
    

    So extend_and_add(a, b) returns:

    extend_and_add(a, b)
    > array([20, 30, 40, 50, 30, 40, 50, 60, 40, 50, 60, 70])
    

    Explanation:

    Basically np.repeat(a, len(b)) repeats:

    a
    > array([ 0, 10, 20])
    

    to

    np.repeat(a, len(b))
    > array([ 0,  0,  0,  0, 10, 10, 10, 10, 20, 20, 20, 20])
    

    after this you need the second array resized with np.resize:

    b
    > array([20, 30, 40, 50])
    

    is resized to:

    np.resize(b, len(a)*len(b))
    > array([20, 30, 40, 50, 20, 30, 40, 50, 20, 30, 40, 50])
    

    Now we can simply add the arrays:

    array([ 0,  0,  0,  0, 10, 10, 10, 10, 20, 20, 20, 20])
    +
    array([20, 30, 40, 50, 20, 30, 40, 50, 20, 30, 40, 50])
    

    returns:

    array([20, 30, 40, 50, 30, 40, 50, 60, 40, 50, 60, 70])
    

提交回复
热议问题