是否存在允许高效范围查询的 python 数据结构?

Is there a python datastructure that would allow efficient range queries?

比如说,你有一个整数列表,例如

foo = [3,9,23,54,77,123,...]

是否有一个高效的数据结构允许像

这样的查询
x = everything in foo between 10 and 100

所以

x == [23,54,77]

或 x = 一切 < 50

给予

x = [3,9,23]

等?

range函数(或python2中的xrange):

foo = [3,9,23,54,77,123]

x = [y for y in foo if y in range(10,101)]
# x = [23,54,77]

如果一侧有无限个数,使用运算符并添加 float(y).is_integer() 以仅匹配整数:

x = [y for y in foo if y < 50 if float(y).is_integer()]
# x = [3,9,23]

假设这些整数已经排序,这不是您想要的数据结构,而是一种算法:即二分查找。在 Python 中,这是由 bisect module 提供的。

因此,例如,要查找小于 50 的所有成员:

from bisect import bisect_left
i = bisect_left(foo, 50)
result = foo[:i]