擅长:python、mysql、java
<p>Python喜欢显式的而不是隐式的。如果知道数据已排序,则可以显式使用<a href="https://docs.python.org/2/library/bisect.html" rel="nofollow">^{<cd1>} module</a>,或者使用该模块创建实现<code>__contains__</code>的<code>list</code>子类。你知道吗</p>
<p>例如:</p>
<pre><code>import bisect
class SortedList(list):
def __contains__(self, elem):
idx = bisect.bisect_left(self, elem)
return idx < len(self) and self[idx] == elem
</code></pre>
<p>可以用作<code>list</code>的替代,并且<code>in</code>将自动使用<code>__contains__</code>。您可能也希望重写<code>__setitem__</code>、<code>.extend()</code>和<code>.append()</code>以保持列表的排序顺序。你知道吗</p>