创建python优先级Queu

2024-04-20 03:13:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python构建一个优先级队列,其中队列包含不同的字典及其优先级编号。因此,当调用“get function”时,优先级最高(数字最低)的字典将被从队列中拉出,当调用“add function”时,新字典将被添加到队列中并根据其优先级数字进行排序。

请帮忙。。。

提前谢谢!


Tags: addget字典排序队列function数字编号
3条回答

在我的一些模式中,这是我通常作为旁注提出的:

class PriorityQueue(object):
 def __init__(self, key=lambda x: x):
   self.l = []
   self.key = key
 def __len__(self):
   return len(self.l)
 def push(self, obj):
   heapq.heappush(self.l, (self.key(obj), obj))
 def pop(self):
   return heapq.heappop(self.l)[-1]

OP的要求显然是在实例化PriorityQueue时使用operator.itemgetter('priority')作为key参数(当然,在模块顶部需要一个import operator;-)。

可以通过向类中添加dict对象并在其中搜索来完成此操作。

使用标准库中的heapq模块。

您不需要指定如何将优先级与字典关联,但这里有一个简单的实现:

import heapq

class MyPriQueue(object):
    def __init__(self):
        self.heap = []

    def add(self, d, pri):
        heapq.heappush(self.heap, (pri, d))

    def get(self):
        pri, d = heapq.heappop(self.heap)
        return d

相关问题 更多 >