python - 函数: Returning min value in dictionary

标签 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.

最佳答案

假设元组是网格上的 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))

关于python - 函数: Returning min value in dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40385898/

相关文章:

python - While循环: UnboundLocalError: local variable referenced before assignment

java - Java 哈希表中的字典

python - 在 Python 2.7 中获取列表长度作为字典中的值

c# - 根据字典输入生成动态方程

javascript - 使用Python中的Tornado模块在handsontable中渲染自定义数据

python - 如何按字典中的值获取键(python 2.7)

python-3.x - 有条件的设置对象的问题

python - Django NOT NULL 约束失败

python - 使用两个不同的环境调用其他Python脚本中的Python脚本

python-3.x - Beautifulsoup 捕获了名字而不是网页的元分数