2016-12-05 81 views
0

最终,我想要的是我要做的是根据他们的分数返回前十名'项目'的列表。我试图实现使用heapq各种各样的优先级队列,到目前为止,我已经得到了什么:根据元组中的第一个值使用Python的heapq.nlargest()检索值

class my_queue: 
    # heap-based priority queue for top items 
    def __init__(self): 
    self.top_items = [] 

    def push_item(self, item): 
    score = item.get_score() 
    item_name = item.get_name() 
    heapq.heappush(self.top_items, (score, item_name)) 

    def top_ten(self): 
    top_ten_items = heapq.nlargest(10, self.top_items, key=lambda s: s[0]) 
    print top_ten_items 

我正在与key=lambda s: s[0]做的是试图理清基于score(score, item_name)堆。有没有简单的方法来完成这个基于我在这里的结构?

感谢。

回答

1

heapq.nlargest是一个等同于:

sorted(iterable, key=key, reverse=True)[:n] 

这意味着呼叫heapq.nlargest(10, self.top_items)将所有项目重新排序,你不会有任何heap数据结构的好处。

heap中的最小项可以用heapq.heappop函数调用获得,因为heap的python实现实际上是min heap

要获得n来自heap的最大项目,您需要将最大项目推到heap(乘以-1)之前最小。例如,像这样:

class my_queue: 
    # heap-based priority queue for top items 
    def __init__(self): 
     self.top_items = [] 

    def push_item(self, item): 
     # minus to make the largest scores the smallest 
     heapq.heappush(self.top_items, (-item.get_score(), item)) 

    def top_ten(self): 
     top_ten_items = [] 
     for i in xrange(10): 
      # minus to revert minus in push_item 
      large_item = -heapq.heappop(self.top_items) 
      top_ten_items.append(large_item) 

     print top_ten_items 
相关问题