创建 python 优先级队列 [英] Creating a python priority Queue

查看:104
本文介绍了创建 python 优先级队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to build a priority queue in python in which the queue contains different dictionaries with their priority numbers. So when a "get function" is called, the dictionary with the highest priority(lowest number) will be pulled out of the queue and when "add function" is called, the new dictionary will be added to the queue and sorted based on its priority number.

请帮忙...

提前致谢!

推荐答案

使用标准库中的 heapq 模块.

Use the heapq module in the standard library.

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

You don't specify how you wanted to associate priorities with dictionaries, but here's a simple implementation:

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

这篇关于创建 python 优先级队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆