我有两个 numpy 数组包含 2d 向量:
import numpy as np
a = np.array([[ 0.999875, 0.015836],
[ 0.997443, 0.071463],
[ 0.686554, 0.727078],
[ 0.93322 , 0.359305]])
b = np.array([[ 0.7219 , 0.691997],
[ 0.313656, 0.949537],
[ 0.507926, 0.861401],
[ 0.818131, 0.575031],
[ 0.117956, 0.993019]])
如您所见,a.shape
is (4,2) 和b.shape
(5,2)。
现在,我可以得到我想要的结果:
In [441]: np.array([np.cross(av, bv) for bv in b for av in a]).reshape(5, 4)
Out[441]:
array([[ 0.680478, 0.638638, -0.049784, 0.386403],
[ 0.944451, 0.924694, 0.423856, 0.773429],
[ 0.85325 , 0.8229 , 0.222097, 0.621377],
[ 0.562003, 0.515094, -0.200055, 0.242672],
[ 0.991027, 0.982051, 0.595998, 0.884323]])
我的问题是:获得上述内容的更“numpythonic”方式是什么(即没有嵌套列表理解)?我已经尝试了所有np.cross()
我能想到的组合,我通常会得到这样的结果:
In [438]: np.cross(a, b.T, axisa=1, axisb=0)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-438-363c0765a7f9> in <module>()
----> 1 np.cross(a, b.T, axisa=1, axisb=0)
D:\users\ae4652t\Python27\lib\site-packages\numpy\core\numeric.p<snipped>
1242 if a.shape[0] == 2:
1243 if (b.shape[0] == 2):
-> 1244 cp = a[0]*b[1] - a[1]*b[0]
1245 if cp.ndim == 0:
1246 return cp
ValueError: operands could not be broadcast together with shapes (4) (5)