使用Python'检索值;s heapq.nlargest()基于元组中的第一个值
最终,我想要的是,我正在尝试返回一个基于分数的前十名“项目”列表。我正在尝试使用heapq实现排序优先级队列,到目前为止,我得到的是:使用Python'检索值;s heapq.nlargest()基于元组中的第一个值,python,priority-queue,Python,Priority Queue,最终,我想要的是,我正在尝试返回一个基于分数的前十名“项目”列表。我正在尝试使用heapq实现排序优先级队列,到目前为止,我得到的是: 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 =
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]
所做的是尝试根据中的分数对堆进行排序(分数,项目名称)
。根据我这里的结构,有没有一个简单的方法来实现这一点
谢谢 相当于:
sorted(iterable, key=key, reverse=True)[:n]
这意味着调用heapq.nlagest(10,self.top_items)
将再次对所有项进行排序,并且您将无法使用heap
数据结构
由于堆
的python实现实际上是最小堆
,因此可以通过函数调用获得堆
中最小的项
要从堆中获取n
最大的项目
,您需要先将最大的项目设置为最小的项目,然后再将其推入堆
(乘以-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