场景:
在日志文件中记录着每次访问的query,现在需要找到最热门的10个query
利用heapq实现
我们首先定义数据结构
class Query(object):
def __init__(self,term,count):
self.term=term
self.count=count
def __cmp__(self,obj):
return cmp(self.count,obj.count)
def __str__(self):
return '%s:%d' %(self.term,self.count)
__repr__ = __str__
现在我们对日志文件根据term进行统计,假设已经得到一个列表 termlist
heapq.heapify(termlist)
#求最大的10个
heapq.nlargest(10,termlist)