在Python中自定义字典查找 [英] Custom dictionary lookup in Python
本文介绍了在Python中自定义字典查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这样的字典
>>> d = {10: 3, 100: 2, 1000: 1}
我可以输入:
>>> d.get(10), d.get(100), d.get(1000)
(3, 2, 1)
虽然我想要的是,如果找不到给定的键,则返回对应于最接近的键的值与给定的键相关的值:
Though I want that if the given key is not found, the value corresponding to the nearest key respect the given key is returned:
>>> d.get(20), d.get(60), d.get(200)
(3, 2, 2)
相反,Python中的结果是
Instead the result in Python is
(None, None, None)
什么是Pythonic的方式来实现我描述的行为?
What's a Pythonic way to implement the behavior I described?
谢谢
推荐答案
您可以从 dict
导出更改行为的 get()
方法:
You can derive from dict
to change the behaviour of the get()
method:
class ClosestDict(dict):
def get(self, key):
key = min(self.iterkeys(), key=lambda x: abs(x - key))
return dict.get(self, key)
d = ClosestDict({10: 3, 100: 2, 1000: 1})
print (d.get(20), d.get(60), d.get(200))
打印
(3, 2, 2)
请注意, get()
不再是O(1),而是O(n)。
Note that the complexity of get()
no longer is O(1), but O(n).
这篇关于在Python中自定义字典查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文