Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python'检索值;s heapq.nlargest()基于元组中的第一个值_Python_Priority Queue - Fatal编程技术网

使用Python'检索值;s heapq.nlargest()基于元组中的第一个值

使用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 =

最终,我想要的是,我正在尝试返回一个基于分数的前十名“项目”列表。我正在尝试使用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 = 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