2012-10-01 27 views

回答

7

裹在反向包装比较的对象:

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) 

用法:

import heapq 
letters = 'axuebizjmf' 
heap = map(ReverseCompare, letters) 
heapq.heapify(heap) 
print heapq.heappop(heap) # prints z 
+0

非常感谢你这是真正的帮助。 –