繁体   English   中英

如何在一组点中找到最接近另一个的点?

[英]How to find point closest to another in a group of points?

假设我有X,Y点的列表。 然后,我添加一个新点,我如何找出新添加的点也最接近哪个旧点? 我已经看到了一些类似的问题,但无济于事。 我正在寻找类似的东西:

pnts = [[11145,1146], [11124,1155], [11212,1147], etc]
new_pnt = [11444, 1160]
new_pnt.closest()

我尝试了scipy和KDTree,并不断收到各种错误。 对Python来说是全新的,任何帮助将不胜感激。

最简单,最快捷的方法是为您定义一个函数,以测量到每个点的距离并返回最接近的点。 例如(假设欧几里得距离):

>>> pnts = [[11145,1146], [11124,1155], [11212,1147]]
>>> new_pnt = [11444, 1160]
>>> def closest(points, new_point):
    closest_point = None
    closest_distance = None
    for point in points:
        distance = ((point[0] - new_point[0])**2 + (point[1] - new_point[1])**2)**0.5
        if closest_distance is None or distance < closest_distance:
            closest_point = point
            closest_distance = distance
    return closest_point

>>> closest(pnts, new_pnt)
[11212, 1147]

您有NumPy吗? 如果是这样的话:

import numpy as np
index = np.argmin(np.sum((np.array(pnts) - np.array(new_pnt))**2, axis=1))
print(index)  # 2

也就是说,点pnts[2]最接近new_pnt 距离由一对x和y坐标之差之和的平方根给出。 在这里,我省略了平方根,因为距离平方最小的点也是距离最小的点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM