有两个像这样的数组
x = [a,b]
y = [p,q,r]
Run Code Online (Sandbox Code Playgroud)
我需要将此乘以一个c类似这样的乘积
c = [a*p, a*q, a*r, b*p, b*q, b*r]
Run Code Online (Sandbox Code Playgroud)
但是x*y,出现以下错误,
ValueError: operands could not be broadcast together with shapes (2,) (3,)
Run Code Online (Sandbox Code Playgroud)
我可以做这样的事情
for i in range(len(x)):
for t in range(len(y)):
c.append(x[i] * y[t]
Run Code Online (Sandbox Code Playgroud)
但真正的长度我x和y相当大有啥做出这样的乘法没有循环的最有效方式。
您可以NumPy broadcasting在x和之间使用成对的逐元素相乘y,然后用展平.ravel(),就像这样-
(x[:,None]*y).ravel()
Run Code Online (Sandbox Code Playgroud)
或使用outer product然后压扁-
np.outer(x,y).ravel()
Run Code Online (Sandbox Code Playgroud)