在列表中找到最接近的点的索引

为了找到最接近的点,我一直在执行该函数时遇到麻烦,我尝试了多种方法来执行此操作,但是似乎无法弄清楚。关于如何解决该问题有任何想法吗?

欧氏距离

def dist(p1, p2):
    x1, y1 = p1
    x2, y2 = p2
    dis = sqrt((x1-x2)**2 + (y1-y2)**2)
    return dis

功能

def offices_to_merge(points):
    min_p1 = 0
    min_p2 = 1
    for i in range(len(points)):
        for j in range(i+1, len(points)):
            dis = dist(points[i], points[j])
            if dis < min((dis)) :
               min_p1 = i
               min_p2 = j
    return (min_p1, min_p2)
>>> points = [(350, 150), (500, 250), (150, 150), (50, 400), (200, 100)]
>>> offices_to_merge(points)
(2, 4)
评论
  • 真凝心
    真凝心 回复

    You can use cdist to get all distances between all points:

    from scipy.spatial.distance import cdist
    import numpy as np
    
    points = [(350, 150), (500, 250), (150, 150), (50, 400), (200, 100)]
    
    # calculate all distances between two sets of points
    dists = cdist(points, points)
    # the self distance is 0 -> we don't want this so make it large
    dists[dists == 0] = dists.max()
    
    # get index of smallest distance
    np.unravel_index(dists.argmin(), dists.shape)
    >>> (2, 4)