Python:从给定的输入键中查找字典中最接近的键 [英] Python: find closest key in a dictionary from the given input key

查看:145
本文介绍了Python:从给定的输入键中查找字典中最接近的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典形式的数据. 现在,我接受用户的输入,它可以是任何东西. 我正在尝试执行以下操作. 如果该键存在,则很酷..从字典中获取值. 如果不是,则获取最接近的值(在数字意义上). 例如..如果输入键是200 按键就像:....

I have a data in form a dictionary.. NOw I take the input from the user and it can be anything.. And I am trying to do the following. If the key exists then cool.. fetch the value from the dictionary. if not, then fetch the nearest (in numeric sense). For example..if the input key is 200 and the keys are like :....

197,202,208...

则可能202是最接近200的键. 现在,从算法的角度来看.它的直截了当..但是有pythonic的方法可以做到这一点吗? 谢谢

Then probably 202 is the closest key to 200.. Now, from algorithm point of view. its straight forward.. but is there a pythonic way to do this? Thanks

推荐答案

以下是您的函数:

data.get(num, data[min(data.keys(), key=lambda k: abs(k-num))])

当键在字典中时不评估最小值,请使用:

edit: to not evaluate the min when the key is in the dict use:

data[num] if num in data else data[min(data.keys(), key=lambda k: abs(k-num))]

,或者如果data中的所有值均评估为True,则可以使用:

or if all values in data evaluate to True you can use:

data.get(num) or data[min(data.keys(), key=lambda k: abs(k-num))]

这篇关于Python:从给定的输入键中查找字典中最接近的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆