简体   繁体   English

字典中的Python最近坐标

[英]Python Closest coordinates in dictionary

I have the following dictionary: 我有以下字典:

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

I am trying to if I have a set of coordinates; 我正在尝试是否有一组坐标; coord = (x, y) to find key with the closest value pairs to the coordinates. coord =(x,y)查找具有最接近坐标值对的键。 But I want retrieve the key that correspond to the closest. 但是我想检索与最接近的键。

I did it this way but there has to be a more efficient way. 我是这样做的,但是必须有一种更有效的方法。

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)])

You don't need to use the list ( array ) at all, you can pass the dictionary ( points ) to min ; 您根本不需要使用列表( array ),可以将字典( points )传递给min key of dictionary will be passed to key function: 字典的键将传递给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'

By accessing coord in lambda directly, you can remove partial : 通过直接访问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)

or 要么

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM