Home > Blockchain >  How to avoid the "for" loop in python
How to avoid the "for" loop in python

Time:11-26

Suppose X is an ndarray with shape (3,8,8), and y is another array with shape (3,). I want to multiply each (8,8) slice of X to one element of y, and then add the resultant. Using a for loop, this can be done as follows:

import numpy as np
X = np.random.rand(3,8,8)
y = np.random.rand(3)
temp = 0
for k in range(3):
    temp = temp y[k]*X[k,:,:]

Is there any way to avoid the "for" loop for this? Any leads are appreciated.

CodePudding user response:

Have you spent enough time reading numpy basics to encounter broadcasting?

(y[:,None,None]*X).sum(axis=0)

should work.

CodePudding user response:

I thought about something like lambda function or list comprehension in the beginning, but could not make it run. Maybe this helps and you can figure it out, I am curious how to solve this too!

  • Related