![从heapq pythond出最大值,Python中有最大堆吗?[重复],第1张 从heapq pythond出最大值,Python中有最大堆吗?[重复],第1张](/aiimages/%E4%BB%8Eheapq+python%E5%BC%B9%E5%87%BA%E6%9C%80%E5%A4%A7%E5%80%BC%EF%BC%8CPython%E4%B8%AD%E6%9C%89%E6%9C%80%E5%A4%A7%E5%A0%86%E5%90%97%EF%BC%9F%5B%E9%87%8D%E5%A4%8D%5D.png)
将对象包装在反向比较包装器中:
import functools@functools.total_orderingclass 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)
用法:
import heapqletters = 'axuebizjmf'heap = map(ReverseCompare, letters)heapq.heapify(heap)print heapq.heappop(heap) # prints z
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)