问题描述
我正在编写一些代码,要求我获取键的下限(为简单起见,忽略位于集合中最小键下方的键).
I am writing some code that requires me to fetch the lower bound of a key (for simplicity, ignore keys that lie below the smallest key in the collection).
在 C++ 中,使用 std::map(作为最具可比性的数据类型)我会简单地使用 lower_bound() 来返回迭代器.
In C++, using std::map (as the most comparable data type) I would simply use the lower_bound() to return the iterator.
我的 Pythonfoo 不是那么好,但我猜测(如果 Python 还没有这样做的方法),这将是 lambda 函数的一个很好的用途......
My Pythonfoo is not that great, but I am guessing that (in case Python does not already have a way of doing this), this would be a good use of a lambda function ...
检索给定索引的下界键的 Pythonic 方法是什么?
What is the Pythonic way of retrieving the lower bound key for a given index?
如果问题太抽象,这就是我真正想做的:
In case the question is too abstract, this is what I am actually trying to do:
我有一个按日期索引的 Python 字典.我希望能够使用日期来查找字典,并返回与指定键的下限相关联的值.
I have a Python dict indexed by date. I want to be able to use a date to look up the dict, and return the value associated with the lowerbound of the specified key.
片段如下:
mymap = { datetime.date(2007, 1, 5): 'foo',
datetime.date(2007, 1, 10): 'foofoo',
datetime.date(2007, 2, 2): 'foobar',
datetime.date(2007, 2, 7): 'foobarbar' }
mydate = datetime.date(2007, 1, 7)
# fetch lbound key for mydate from mymap
def mymap_lbound_key(orig):
pass # return the lbound for the key
我真的不想遍历键,寻找第一个键 <= 提供的键,除非没有更好的选择...
I don't really want to loop through the keys, looking for the first key <= provided key, unless there is no better alternative ...
推荐答案
Python 的 dict
类没有这个功能;你需要自己写.如果键已经排序,那肯定会很方便,不是吗,所以你可以对它们进行二分搜索并避免对它们进行迭代?在这种情况下,我将查看 blist
包中的 sorteddict
类.http://pypi.python.org/pypi/blist/
Python's dict
class doesn't have this functionality; you'd need to write it yourself. It sure would be convenient if the keys were already sorted, wouldn't it, so you could do a binary search on them and avoid iterating over them all? In this vein, I'd have a look at the sorteddict
class in the blist
package. http://pypi.python.org/pypi/blist/
这篇关于map::lower_bound() 等效于 python 的 dict 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!