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

后端 未结 7 725
野的像风
野的像风 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:44

    I feel the simplest way is to override the existing cmp_lt function of the heapq module. A short example:

    import heapq
    
    # your custom function. Here, comparing tuples a and b based on their 2nd element
    def new_cmp_lt(self,a,b):
        return a[1]

提交回复
热议问题