【发布时间】:2017-03-26 06:37:21
【问题描述】:
我有以下字典:
points = {'Location1': (76, 81), 'Location2': (75, 105), 'Location3': (76, 130), 'Location4': (76, 152)}
如果我有一组坐标,我正在尝试; coord = (x, y) 找到与坐标最接近的值对的键。但我想检索与最接近的键对应的键。
我是这样做的,但必须有更有效的方法。
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)])
【问题讨论】:
标签: python list python-3.x dictionary