擅长:python、mysql、java
<p>只需为列表中的对象编写一个适当的<code>__lt__</code>方法,以便它们正确排序:</p>
<pre><code>class FirstList(list):
def __lt__(self, other):
return self[0] < other[0]
lst = [ ['a', 3], ['b', 1] ]
lst = [FirstList(item) for item in lst]
</code></pre>
<p>Python只需要<code>__lt__</code>来进行排序,不过最好定义所有比较或使用<a href="https://docs.python.org/2/library/functools.html#functools.total_ordering" rel="noreferrer">^{<cd3>}</a>。</p>
<p>您可以看到它是通过使用具有相同第一值和不同第二值的两个项来工作的。当您<code>heapify</code>时,无论第二个值是什么,这两个对象都将交换位置,因为<code>lst[0] < lst[1]</code>将始终是<code>False</code>。如果你需要稳定的<code>heapify</code>,你需要一个更复杂的比较。</p>