函数:在字典

时间:2016-11-02 17:15:00

标签: python python-3.x dictionary

我很难理解字典功能。我试图写的函数需要找到当前位置所在的最近位置(在字典中给出)并将其返回。我告诉我们有一个距离公式,但不知道如何将它实现到函数字典中。如果找不到任何内容,则应该不返回任何内容。

def closest_location(d, place, now):
        close_lst = []# New list
        for d in closest.place():
            for d in closest.now():
                if now != place:
                    return None
                elif now <= place: #If location at now is less than place we want to go to...
                    close_val = now - place
                close_lst.append(close_val)
        return(min(d, key=close_lst.get))# returns closest value in list?

试验:

check that closest({(3,1):'gas', (1,4):'gas', (2,1):'food', (5,5):'food'},'food',(5,5)) == (5,5).
check that closest({(3,1):'gas', (1,4):'gas', (2,1):'food', (5,5):'food'},'hotel',(1,4)) == None.

1 个答案:

答案 0 :(得分:2)

假设元组是网格上的x,y坐标,距离公式由毕达哥拉斯给出:

(x1 - x2)^2 + (y1 - y2)^2 = distance^2

为了便于阅读,我们将把它拉到它自己的功能中。

from math import sqrt
def find_distance(a,b):
    ax, ay = a
    bx, by = b
    return sqrt((ax-bx)**2 + (ay-by)**2)

def closest_location(d, place, now):
    locations = [loc for loc, attraction in d.items() if attraction==place]
    if not locations:
        return None
    else:
        return min(locations, key=lambda x: find_distance(x, now))