【问题标题】:Creating a python priority Queue创建一个python优先队列
【发布时间】:2011-03-19 16:42:36
【问题描述】:

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

请帮忙...

提前致谢!

【问题讨论】:

    标签: python priority-queue task-queue


    【解决方案1】:

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

    【讨论】:

    • 我希望它可以是这种格式: 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': None, 'priority': 1 } #将字典添加到语音中的全局队列并打印 #使用循环队列 speech.add_to_queue(firstDict) speech.add_to_queue(secondDict) 语音。 add_to_queue(thirdDict) speech.loop_queue()
    • 请问我是否获得了代码格式,以便在正确的格式下以更好的方式出现。谢谢!
    • @fabramma,你问“我如何获得代码格式”:答案是,把你的代码放在你的 question 中,not 在评论!我怀疑这是 SO 中经过深思熟虑的设计决定:它促使您编辑问题以使其清晰和完整(代码示例和所有内容),并且转向长评论线程。无论如何,要使您的代码工作,而不是仅仅格式化好;-),请参阅我对这个问题的回答;-)。
    【解决方案2】:

    这是我通常在我的一些模式演讲中作为旁注呈现的内容:

    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;-)。

    【讨论】:

      【解决方案3】:

      你可以通过向类中添加一个 dict 对象来做到这一点,并在里面搜索它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-11
        • 2023-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多