Python 如何使用对象比较函数反转heapq堆中元素的顺序?
首先,我读了这篇文章,但它实际上没有包括我想要的方法。此外,否定实际值不适用于我的用例 Heapq文件: 假设我的堆中有一个dataclass对象列表。只有a特性确定对象的顺序Python 如何使用对象比较函数反转heapq堆中元素的顺序?,python,python-3.x,heap,python-3.6,Python,Python 3.x,Heap,Python 3.6,首先,我读了这篇文章,但它实际上没有包括我想要的方法。此外,否定实际值不适用于我的用例 Heapq文件: 假设我的堆中有一个dataclass对象列表。只有a特性确定对象的顺序 import heapq from dataclasses import dataclass @dataclass class C: a: int b: int def __lt__(self, other): return self.a < other.a l=[C(2
import heapq
from dataclasses import dataclass
@dataclass
class C:
a: int
b: int
def __lt__(self, other):
return self.a < other.a
l=[C(2,1),C(9,109),C(2,4),C(9,4)]
print(heapq.heappop(l)) # C(a=2, b=1)
print(heapq.heappop(l)) # C(a=2, b=4)
print(heapq.heappop(l)) # C(a=9, b=109)
print(heapq.heappop(l)) # C(a=9, b=4)
预期结果应为四种解决方案之一:
C(a=9, b=109) C(a=9, b=4) C(a=9, b=109) C(a=9, b=4)
C(a=9, b=4) C(a=9, b=109) C(a=9, b=4) C(a=9, b=109)
C(a=2, b=1) C(a=2, b=1) C(a=2, b=4) C(a=2, b=4)
C(a=2, b=4) C(a=2, b=4) C(a=2, b=1) C(a=2, b=1)
也许,并不是所有的对象对都通过heapq进行比较,这可以解释奇怪的顺序。然而,是否仍然可以得到一个颠倒的顺序
我是否必须提供更多的对象比较方法
object.__lt__(self, other)
object.__le__(self, other)
object.__eq__(self, other)
object.__ne__(self, other)
object.__gt__(self, other)
object.__ge__(self, other)
如果你有完全不同的方法,不要犹豫 您需要使用
印刷品
C(a=9, b=4)
C(a=9, b=109)
C(a=2, b=1)
C(a=2, b=4)
但为什么在我问题的第一个案例中它起作用?列表没有排序。因为示例列表在
from heapq import heapify, heappop
from dataclasses import dataclass
@dataclass
class C:
a: int
b: int
def __lt__(self, other):
return self.a > other.a
l=[C(2,1),C(9,109),C(2,4),C(9,4)]
heapify(l)
while l:
print(heappop(l))
C(a=9, b=4)
C(a=9, b=109)
C(a=2, b=1)
C(a=2, b=4)