删除Numpy数组上的for循环

I have three two dimensional Numpy arrays x, w, d and want to create a fourth one called a. w and d define only the shape of a with d.shape + w.shape. I want to have x in the entries of a with a zeros elsewhere. Specifically, I want a loop-free version of this code:

a = np.zeros(d.shape + w.shape)

for j in range(d.shape[1]):
    a[:,j,:,j] = x

例如,给定:

x = np.array([
    [2, 3],
    [1, 1],
    [8,10],
    [0, 1]
])

w = np.array([
    [ 0, 1, 1],
    [-1,-2, 1]
])

d = np.matmul(x,w)

I want a to be

array([[[[ 2.,  0.,  0.],
         [ 3.,  0.,  0.]],

        [[ 0.,  2.,  0.],
         [ 0.,  3.,  0.]],

        [[ 0.,  0.,  2.],
         [ 0.,  0.,  3.]]],


       [[[ 1.,  0.,  0.],
         [ 1.,  0.,  0.]],

        [[ 0.,  1.,  0.],
         [ 0.,  1.,  0.]],

        [[ 0.,  0.,  1.],
         [ 0.,  0.,  1.]]],


       [[[ 8.,  0.,  0.],
         [10.,  0.,  0.]],

        [[ 0.,  8.,  0.],
         [ 0., 10.,  0.]],

        [[ 0.,  0.,  8.],
         [ 0.,  0., 10.]]],


       [[[ 0.,  0.,  0.],
         [ 1.,  0.,  0.]],

        [[ 0.,  0.,  0.],
         [ 0.,  1.,  0.]],

        [[ 0.,  0.,  0.],
         [ 0.,  0.,  1.]]]])
评论