虽然可以使用向量化,但使用numpy数组时,@ Karl的方法将相当慢。
更简单的方法就是这样做np.hypot(*(points - single_point).T)
。(转置假定点是Nx2数组,而不是2xN。如果是2xN,则不需要.T
。
但是,这有点难以理解,因此您可以像这样(用一些罐头示例数据…)更明确地将其写出:
import numpy as np
single_point = [3, 4]
points = np.arange(20).reshape((10,2))
dist = (points - single_point)**2
dist = np.sum(dist, axis=1)
dist = np.sqrt(dist)