How to make heapq evaluate the heap off of a specific attribute?

后端 未结 7 732
野的像风
野的像风 2020-11-30 22:07

I wish to hold a heap of objects, not just numbers. They will have an integer attribute in them that the heap can sort by. The easiest way to use heaps in python is heapq,

7条回答
  •  青春惊慌失措
    2020-11-30 22:51

    heapq sorts objects the same way list.sort does, so just define a method __cmp__() within your class definition, which will compare itself to another instance of the same class:

    def __cmp__(self, other):
        return cmp(self.intAttribute, other.intAttribute)
    

    Works in Python 2.x.

    In 3.x use:

    def __lt__(self, other):
        return self.intAttribute < other.intAttribute
    

提交回复
热议问题