Search code examples
pythonarrayspython-3.xlistnested

Multiply different size nested array with scalar


In my python code, I have an array that has different size inside like this

arr = [
    [1],
    [2,3], 
    [4],
    [5,6,7],
    [8],
    [9,10,11]
]

I want to multiply them by 10 so it will be like this

arr = [
        [10],
        [20,30], 
        [40],
        [50,60,70],
        [80],
        [90,100,110]
    ]

I have tried arr = np.multiply(arr,10) and arr = np.array(arr)*10

it seems that both are not working for different size of nested array because when I tried using same size nested array, they actually works just fine


Solution

  • It is best to just use a nested loop :

    arr = [
        [1],
        [2,3], 
        [4],
        [5,6,7],
        [8],
        [9,10,11]
    ]
    
    def matrix_multiply_all(matrix,nb):
        return list(map(lambda arr : list(map(lambda el : el*nb,arr)),matrix))
    print(matrix_multiply_all(arr,10))