我不明白为什么我的下面的代码会引发错误。
我正在尝试基于Python的heapq模块构建一个优先级列表。 与模块的基本示例的唯一区别是希望将其与其中的自定义对象一起使用,而不是简单的 (int,int) 或 (int,str) 元组。
import heapq
class MyObject():
def __init__(self,a=0,name='toto'):
self.a = a
self.name = name
if __name__ == '__main__':
priority_list = []
heapq.heappush(priority_list,(1,MyObject()))
heapq.heappush(priority_list,(1,MyObject()))
这是我的错误:
heapq.heappush(priority_list,(1,MyObject()))
TypeError: '<' not supported between instances of 'MyObject' and 'MyObject'
如果我使用不同的键插入堆中,则不会引发错误,但 heapq 不应该处理相同的键吗? 我不太理解这种行为。
非常感谢
最佳答案
运算符(operator)<
没有为您的类(class)定义。那样heapq
无法定义优先级。
ob1 = MyObject()
ob1 < ob1
加薪
TypeError: unorderable types: MyObject() < MyObject()
然后您必须定义逻辑运算符。请参阅this了解更多信息。
class MyObject():
def __init__(self,a=0,name='toto'):
self.a = a
self.name = name
def __lt__(ob1, ob2):
return ob1.a < ob2.a
ob1 = MyObject()
ob1 < ob1 # returns False
关于python - 在 python 中使用 heapq 获取优先级列表时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49277168/