在 Python 中使用欧氏距离确定最近的位置

Determine closest location using euclidian distance in Python

所以我正在努力从字典中的数据中找到两个坐标的最近欧氏距离。
首先,我已经弄清楚如何使用以下方法计算两个笛卡尔坐标 (x,y) 之间的距离:

from math import sqrt
def distance(loc1_coordinates, loc2_coordinates):
    point1x, point1y = loc1_coordinates
    point2x, point2y = loc2_coordinates
    Distance = sqrt((point1x-point2x)**2 + (point1y-point2y)**2)  
    return "The distance between this two points is", str(round(Distance, 14))+" units"

print(distance([0,0],[3,4])) # distance should be 5.0

如何在我之前的函数的基础上创建一个新函数,以便得到以下结果?

cities = {'A':[5,21], 'B':[43,76], 'C':[56,19], 'D':[21,37], 'E':[76,23], 'F':[45,56], 'G':[23,13]}
print(closest_destination('A', cities)) # should be 'G'

更新:我试图在输入城市的计算列表中找到最小距离:例如:比较 A->B、A->C、A->D,...并选择一个谁距离最近

首先,将您的函数更改为 return 数值而不是字符串(通常,您应该具有函数 return 值,这样您就可以在代码中用它们做其他有用的事情,而不是将它们变成英语表示形式):

from math import sqrt
def distance(loc1_coordinates, loc2_coordinates):
    point1x, point1y = loc1_coordinates
    point2x, point2y = loc2_coordinates
    return sqrt((point1x-point2x)**2 + (point1y-point2y)**2)  

您可以使用此函数做的一个有用的事情是将其用作 min 函数中的 key 以查找最小距离:

def closest_destination(city: str, cities: dict) -> str:
    """Given a city in a {city: coord} dict, return closest other city."""
    other_cities = {k: v for k, v in cities.items() if k != city}
    return min(other_cities, key=lambda o: distance(cities[o], cities[city]))

然后:

cities = {'A':[5,21], 'B':[43,76], 'C':[56,19], 'D':[21,37], 'E':[76,23], 'F':[45,56], 'G':[23,13]}
print(closest_destination('A', cities)) # prints 'G'

单遍方法是使用 min:

的关键参数
def closest_destination(source, locations):
    source_location = locations[source]
    return min(locations, key=lambda loc: (loc == source, distance(source_location, locations[loc])))


cities = {'A': [5, 21], 'B': [43, 76], 'C': [56, 19], 'D': [21, 37], 'E': [76, 23], 'F': [45, 56], 'G': [23, 13]}
print(closest_destination('A', cities))  # should be 'G'

输出

G

函数思路:

lambda loc: (loc == source, distance(source_location, locations[loc]))

将每个 city 键映射到一个元组,如果它等于源,则第一个值为 1,因此它总是排在最后。然后你按距离打破关系。