简体   繁体   English

在python中使用heapq作为优先级列表的问题

[英]Issue using heapq in python for a priority list

I can't understand why my below code raise an error. 我无法理解为什么我的下面的代码会引发错误。

I'm trying to build a priority list based on heapq module of Python. 我正在尝试基于Python的heapq模块构建优先级列表。 The only difference with a basic example of the module is that want to use it with custom objects in it it, instead of simple (int,int) or (int,str) tuples. 与模块的基本示例的唯一区别是希望将其与自定义对象一起使用,而不是简单(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()))

This is the error I have: 这是我的错误:

heapq.heappush(priority_list,(1,MyObject()))

TypeError: '<' not supported between instances of 'MyObject' and 'MyObject'

The error is not raised if I use a different key to insert in the heap, but isn't heapq supposed to deal with same keys? 如果我使用不同的密钥插入堆中,但不是heapq应该处理相同的密钥,则不会引发错误? I don't understand very well this behaviour. 我不太了解这种行为。

Thanks a lot 非常感谢

The operator < is not defined for your class. 运算符<未定义为您的类。 That way heapq can't define priority. 这样heapq就无法定义优先级。

ob1 = MyObject()
ob1 < ob1

raises 加薪

TypeError: unorderable types: MyObject() < MyObject()

You must then define the logical operators. 然后,您必须定义逻辑运算符。 See this for more info. 有关详细信息,请参阅

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

A heap has the property that the smallest object is always on top. 堆具有最小对象始终位于顶部的属性。 In order for Python to preserve that invariant, it must have some way of determining which object is smaller. 为了使Python保留该不变量,它必须有一些方法来确定哪个对象更小。 Your MyObject class does not provide this. 您的MyObject类不提供此功能。

You can define __gt__ or __lt__ to enable this. 您可以定义__gt____lt__来启用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM