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)
然后:
>>> 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
Python喜欢显式的而不是隐式的。如果知道数据已排序,则可以显式使用^{} module ,或者使用该模块创建实现
__contains__
的list
子类。你知道吗例如:
可以用作
list
的替代,并且in
将自动使用__contains__
。您可能也希望重写__setitem__
、.extend()
和.append()
以保持列表的排序顺序。你知道吗我的建议是子类list来使用排序list:
然后:
相关问题 更多 >
编程相关推荐