来自heapq python的pop max值,Python中是否有最大堆?

Mik*_*e B 2 python min-heap max-heap

可能重复:
我在Python中使用什么来实现最大堆实现?

我试图以某种方式实现python的heapq但是对于max-heap.一个解决方案是使用(-1)和多个队列号,但这对我没有帮助,因为我需要将URL存储在堆中.所以我想要一个max heapq,我可以弹出最大的值.

nne*_*neo 8

将对象包装在反向比较包装器中:

import functools

@functools.total_ordering
class ReverseCompare(object):
    def __init__(self, obj):
        self.obj = obj
    def __eq__(self, other):
        return isinstance(other, ReverseCompare) and self.obj == other.obj
    def __le__(self, other):
        return isinstance(other, ReverseCompare) and self.obj >= other.obj
    def __str__(self):
        return str(self.obj)
    def __repr__(self):
        return '%s(%r)' % (self.__class__.__name__, self.obj)
Run Code Online (Sandbox Code Playgroud)

用法:

import heapq
letters = 'axuebizjmf'
heap = map(ReverseCompare, letters)
heapq.heapify(heap)
print heapq.heappop(heap) # prints z
Run Code Online (Sandbox Code Playgroud)