Multiplication of n shape list with n shape arrays elementwise in one line

Viewed 72

Let's take an example:

w =[1, 2] # as list
p = [[[1, 2], [3, 4]], [[4, 5], [6, 7]]] # as array

The output should be:

output =[[[1, 2], [3, 4]], [[8, 20], [12, 14]]]

However, I wanted to have it done in one line. I am looking for a function that can take the arguments w and p and return output.

Example using for loop:

dummy_array = np.zeros(shape=(2,2))

for i in range(2):
    output[i]= w[i]*p[i]
1 Answers

I'm under the assumption you specifically want to use lists, if so then you could use the following one-liner (I'm assuming you had a mistake and you meant the output to be [[[1, 2], [3, 4]], [[8, 10], [12, 14]]]).

import numpy as np
p = [[[1, 2],[3, 4]], [[4, 5], [6, 7]]]
w = [1, 2]
output = [(np.array(p_curr)*w_curr).tolist() for p_curr, w_curr in zip(p,w)]

If you want to use numpy (this is usually the standard package for these types of operations), you can multiply along the axis you'd like. For example, we could do:

import numpy as np
p = np.array([[[1, 2], [3, 4]], [[4, 5], [6, 7]]])
w = np.array([1, 2])[:, np.newaxis, np.newaxis]
output = p*w

Note I added two new axes, and left the original (2) dimension to correspond with what you wanted to be multiplied. Meaning, if you take the code snippet and check p[0,:,:], you'd get:

array([[1, 2],
   [3, 4]])

Which corresponds to the first element of your original list.

Related