Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.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优先级队列_Python_Priority Queue_Task Queue - Fatal编程技术网

创建python优先级队列

创建python优先级队列,python,priority-queue,task-queue,Python,Priority Queue,Task Queue,我想用python构建一个优先级队列,其中队列包含不同的字典及其优先级编号。因此,当调用“get函数”时,具有最高优先级(最低编号)的字典将从队列中拉出,当调用“add函数”时,新字典将添加到队列中,并根据其优先级编号进行排序 请帮帮忙 提前谢谢 使用标准库中的heapq模块 您没有指定如何将优先级与字典关联,但这里有一个简单的实现: import heapq class MyPriQueue(object): def __init__(self): self.heap

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

请帮帮忙


提前谢谢

使用标准库中的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

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

这是我在一些模式讲座中通常作为旁注介绍的内容:

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
时使用
操作符.itemgetter('priority')
作为
参数(当然,在模块顶部需要一个
导入操作符
)。

我希望它可以是这样的格式:if name='main':speech=Speak()firstDict={'command_type':'say_string','control_command':'stop','priority':3}secondDict={'command_type':'say_string','control_command':'resume','priority':2}thirdDict={'command_type':'say_wav','control_command':无,'priority':1}#将字典添加到语音中的全局队列并打印它们#使用循环队列语音。添加到队列(第一个dict)语音。添加到队列(第二个dict)语音。添加到队列(第三个dict)语音。循环队列()请hw我是否获得代码格式,以便它看起来更适合正确的格式。谢谢!@fabramma,你问“如何获取代码格式”:答案是,将代码放在问题中,而不是放在注释中!我怀疑这是一个深思熟虑的设计决策,因此:它促使您编辑问题以使其清晰完整(代码示例和所有内容),而不是转向长注释线程。无论如何,要使代码正常工作,而不仅仅是良好地格式化;-),请参阅我对这个问题的回答;-)。