2016-12-05 16 views
0

最終的に、私がしたいのは、スコアに基づいてトップ10の項目のリストを返すことです。私はheapqを使用して一種のプライオリティキューを実装しようとすると、これまでのところ、私が持っているものであるのです。私はkey=lambda s: s[0]でやっていることは(score, item_name)からscoreに基づいてヒープをソートするためにしようとしているタプルの最初の値に基づいて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 

。ここにある構造に基づいてこれを達成する簡単な方法はありますか?

ありがとうございました。これは、コールheapq.nlargest(10, self.top_items)が再びすべての項目をソートし、あなたがheapデータ構造の何のメリットを持っていないことを意味

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

答えて

1

heapq.nlargestは同等です。 heapのPython実装は、実際min heapあるのでheap

最小アイテムは、heapq.heappop関数呼び出しを得ることができます。

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 
関連する問題