python寻找距离最近的点,在Python中找到两个列表的点之间的最小距离

I have two lists of coordinates:

s1 = [(0,0), (0,1), (1,0), (1,1)]

s2 = [(3,2), (1,9)]

I want to calculate the minimum distance of each point in s1 to any point in s2. e.g. the results should be as follows.

result = [3.60, 3.16, 2.82, 2.23]

Question: What is the most optimized way in terms of execution time, to achieve this result?

So far I've tried this but the execution time is not promising:

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))

Should I change the structure of s1 and s2 (instead of points use 2d arrays for example)?

解决方案

The easiest way is probably to use scipy.spatial.distance.cdist:

import numpy as np

from scipy.spatial import distance

s1 = np.array([(0,0), (0,1), (1,0), (1,1)])

s2 = np.array([(3,2), (1,9)])

print(distance.cdist(s1,s2).min(axis=1))

# array([3.60555128, 3.16227766, 2.82842712, 2.23606798])

Some more speed might be gained by directly outputting 0 for any point from s1 that is also in s2.

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值