块状乘以不同的形状

问题描述:

有两个像这样的数组

x = [a,b]
y = [p,q,r]

我需要将此乘以一个乘积c,它应该像这样,

I need to multiply this together to a product c which should be like this,

c = [a*p, a*q, a*r, b*p, b*q, b*r]

但是x*y出现以下错误,

ValueError: operands could not be broadcast together with shapes (2,) (3,)

我可以做这样的事情,

for i in range(len(x)):
    for t in range(len(y)):
        c.append(x[i] * y[t]

但是我的xy的长度确实很大,所以在没有循环的情况下进行这种乘法的最有效方法是什么.

But really the length of my x and y is quite large so what's the most efficient way to make such a multiplication without the looping.

您可以使用

You can use NumPy broadcasting for pairwise elementwise multiplication between x and y and then flatten with .ravel(), like so -

(x[:,None]*y).ravel()

或使用 outer product ,然后将其展平-

Or use outer product and then flatten -

np.outer(x,y).ravel()