擅长:python、mysql、java
<p>恐怕只有heapq没有这种方法。因为从堆中搜索元素需要<code>O(n)</code>。</p>
<p>但是您可以将它与<code>dict</code>一起使用,这样可以给<code>O(1)</code>时间来搜索条目。</p>
<p><strong>更新:</strong></p>
<blockquote>
<p>I tried using a dict for bookkeeping, but how can I get the index of "create test" when it was inserted? – Prakhar 3 hours ago</p>
</blockquote>
<p>天真的做法是:</p>
<pre><code># remember to update this hdict when updating the heap.
hdict = { h[i][1]: i for i in range(len(h)) }
</code></pre>
<p>然后,您可以通过访问这个<code>hdict</code>而不是您的<code>O(n)</code>线性搜索来获取给定字符串的索引。</p>