python隐式二进制搜索
我有一个已经排序的列表 我经常需要去看看python隐式二进制搜索,python,performance,Python,Performance,我有一个已经排序的列表 我经常需要去看看 if foo in sortedlist: pass # not really. but not the point. 有没有一种方法可以教“in”sortedlist被排序,并且它应该对列表进行二进制搜索?Python倾向于显式而不是隐式。如果您知道数据已排序,则可以显式使用,或者通过使用该模块创建实现\uuuu contains\uuu的列表的子类 例如: import bisect class SortedList(list):
if foo in sortedlist:
pass # not really. but not the point.
有没有一种方法可以教“in”sortedlist被排序,并且它应该对列表进行二进制搜索?Python倾向于显式而不是隐式。如果您知道数据已排序,则可以显式使用,或者通过使用该模块创建实现
\uuuu contains\uuu
的列表的子类
例如:
import bisect
class SortedList(list):
def __contains__(self, elem):
idx = bisect.bisect_left(self, elem)
return idx < len(self) and self[idx] == elem
导入对分
分类列表(列表):
定义包含(自身,元素):
idx=对分。左对分(自,元素)
返回idx
可以用作
列表
的替代品,并且中的将自动使用\uuuu包含
。您可能希望重写\uuuu setitem\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
from bisect import bisect_left
class SortedList(list):
def __init__(self, l):
list.__init__(self, sorted(l))
def __contains__(self, obj):
pos = bisect_left(self, obj, 0, len(self))
return (pos != len(self) and self[pos] == obj)
然后:
可能重复的好问题-最好知道如何在排序(我的列表)中进行搜索。不可能更改“in”的行为。你要找的是马特·鲍尔(Matt Ball)所指的链接(可能重复)。@threadp:不完全正确。如下所示。@MartijnPieters:您的代码不正确:如果elem大于列表中的最大元素,它将引发索引器:列表索引超出范围
:返回的idx
是len(self)
@MartijnPieters不在我的机器上。。。你一定要检查一下你的。@hivert:啊,不,我确实忘记了elem>self[-1]
的情况。谢谢你指出这一点。更正。
>>> l = SortedList([4,3,5435,123,54,2,343,23])
>>> l
[2, 3, 4, 23, 54, 123, 343, 5435]
>>> 23 in l
True
>>> 25 in l
False
>>> 123122 in l
False
>>> -1 in l
False