gpt4 book ai didi

Python字典中最近的坐标

转载 作者:太空宇宙 更新时间:2023-11-03 11:44:14 25 4
gpt4 key购买 nike

我有以下字典:

points = {'Location1': (76, 81), 'Location2': (75, 105), 'Location3': (76, 130), 'Location4': (76, 152)}

如果我有一组坐标,我正在尝试; coord = (x, y) 找到与坐标最接近的值对的键。但我想检索对应于最近的 key 。

我是这样做的,但必须有更有效的方法。

points = {'Location1': (76, 81), 'Location2': (75, 105), 'Location3': (76, 130), 'Location4': (76, 152)}
array = [(76, 81), (75, 105), (76, 130), (76, 152)]

def find_nearest(array,coord):

dist = lambda s, d: (s[0] - d[0]) ** 2 + (s[1] - d[1]) ** 2

result = min(array, key=partial(dist, coord))

return result

found = find_nearest(array,coord)

print (list(points.keys())[list(points.values()).index(found)])

最佳答案

你根本不需要使用列表(array),你可以将字典(points)传递给min;字典的键将传递给 key 函数:

>>> from functools import partial
>>>
>>> def find_nearest(points, coord):
... dist = lambda s, key: (s[0] - points[key][0]) ** 2 + \
... (s[1] - points[key][1]) ** 2
... return min(points, key=partial(dist, coord))
...
>>> points = {'Location1': (76, 81), 'Location2': (75, 105),
... 'Location3': (76, 130), 'Location4': (76, 152)}
>>> find_nearest(points, (0, 0))
'Location1'
>>> find_nearest(points, (100, 100))
'Location2'
>>> find_nearest(points, (100, 200))
'Location4'

通过直接访问 lambda 中的 coord,您可以删除 partial:

def find_nearest(points, coord):
dist = lambda key: (coord[0] - points[key][0]) ** 2 + \
(coord[1] - points[key][1]) ** 2
return min(points, key=dist)

def find_nearest(points, coord):
x, y = coord
dist = lambda key: (x - points[key][0]) ** 2 + (y - points[key][1]) ** 2
return min(points, key=dist)

关于Python字典中最近的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43025854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com