簡體   English   中英

字典中的Python最近坐標

[英]Python Closest coordinates in dictionary

我有以下字典:

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

您根本不需要使用列表( 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM