我有两个坐标列表:
s1 = [(0,0), (0,1), (1,0), (1,1)]
s2 = [(3,2), (1,9)]
我想计算 s1 中每个点到 s2 中任意点的最小距离。例如,结果应该如下。
result = [3.60, 3.16, 2.82, 2.23]
问题: 为了达到这个结果,在执行时间方面最优化的方法是什么?
到目前为止,我已经试过了,但执行时间并不乐观:
import math
def nearestDistance(boundary, p):
minDistList = map(lambda b: (b[0] - p[0])**2 + (b[1] - p[1])**2, boundary)
minDist2 = min(minDistList)
return math.sqrt(float(minDist2))
d = []
for p in s1:
d.append(nearestDistance(s2, p))
我是否应该更改 s1 和 s2 的结构(而不是点,例如使用二维数组)?
原文由 orak 发布,翻译遵循 CC BY-SA 4.0 许可协议
最简单的方法可能是使用
scipy.spatial.distance.cdist
:对于来自
s1
0
也可以在s2
中获得更多速度。