如何从点列表中找到最近的坐标?

How to find the closest coordinate from a list of points?

假设我有一个 x, y 坐标列表如下:

A = [(26, 63), (23, 63), (22, 63), (21, 63), (20, 63), (22, 62), (27, 63)] 

我有一个点的 x, y 坐标如下:

leftbottom = (0, 238)

现在,我想在列表 A 中找到最接近 leftbottom 点的点。

我怎样才能最有效地做到这一点?

您可以使用 numpy:

import numpy as np

A = [(26, 63), (25, 63), (24, 63), (23, 63), (22, 63), (21, 63), (20, 63), (22, 62), (27, 63)]
p = (0, 238)

xy = np.array(A).T

# euclidean distance
d = ( (xy[0] - p[0]) ** 2 + (xy[1] - p[1]) ** 2) ** 0.5

closest_idx = np.argmin(d)
closest = A[closest_idx]

print(closest)

(20, 63)

Numpy 有一个有用的函数:norm。

import numpy as np
A = [(26, 63), (25, 63), (24, 63), (23, 63), (22, 63), (21, 63), (20, 63), (22, 62), (27, 63)]
A = np.array(A)
leftbottom = np.array((0,238))
distances = np.linalg.norm(A-leftbottom, axis=1)
min_index = np.argmin(distances)
print(f"the closest point is {A[min_index]}, at a distance of {distances[min_index]}")

结果:

the closest point is [20 63], at a distance of 176.13914953808538

你可以简单地在python中得到最近的坐标。

假设 leftbottom 与 A​​ 具有相同的格式。

leftbottom = [(x,y)]

import numpy as np
diffs = np.abs(np.array(A)-np.array(leftbottom))
dists = np.sum(dists,axis=1) #l1-distance
closest_point_index = np.argmin(dists)

如果您正在寻找不使用 numpy 的解决方案,也许这可以帮助您

  from math import sqrt
  def min_distance(x, y, iterable):
       list_of_distances = list(map(lambda t: sqrt(pow(t[0]-x,2)+pow(t[1]-y,2)),iterable))
       min_res = min(list_of_distances)
       index_of_min = list_of_distances.index(min_res)
       return iterable[index_of_min]
   
   A = [(26, 63), (25, 63), (24, 63), (23, 63), (22, 63),(21, 63), (20, 63), (22, 62), (27, 63)]
   
   
  a = min_distance(0, 238, A)
  print(a)

这是一个内置的解决方案,使用 min() function over the list of points with the key argument being the distance of each point to the target point, calculated with math.hypot:

import math

points = [(26, 80), (23, 24), (22, 63), (2, 63)] 
target = (1, 63)

print(min(points, key=lambda point: math.hypot(target[1]-point[1], target[0]-point[0])))

在此示例中,将打印 (2, 63)