Python利用heapq实现一个优先级队列的方法
作者:LazyCat_CiCi 时间:2021-08-05 06:28:48
实现一个优先级队列,每次pop的元素要是优先级高的元素,由于heapq.heapify(list)默认构建一个小顶堆,因此要将priority变为相反数再push,代码如下:
import heapq
class PriorityQueue(object):
"""实现一个优先级队列,每次pop优先级最高的元素"""
def __init__(self):
self._queue = []
self._index = 0
def push(self,item,priority):
heapq.heappush(self._queue,(-priority,self._index,item))#将priority和index结合使用,在priority相同的时候比较index,pop先进入队列的元素
self._index += 1
def pop(self):
return heapq.heappop(self._queue)[-1]
if __name__ == '__main__':
pqueue = PriorityQueue()
pqueue.push('d',4)
pqueue.push('f',3)
pqueue.push('a',6)
pqueue.push('s',2)
print(pqueue.pop())
print(pqueue.pop())
print(pqueue.pop())
来源:https://blog.csdn.net/Jmiew123/article/details/68951054
标签:Python,heapq,优先,队列
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Mysql数据库备份和还原常用的命令
2011-12-01 10:41:54
Python实现比较两个列表(list)范围
2022-07-20 18:08:04
JavaScript监听和禁用浏览器回车事件实例
2023-10-12 01:58:16
动易CMS:九个常见的错误原因分析及解决方法(ZT)
2008-07-01 12:40:00
真正保险的“有属性”检测
2010-03-28 13:25:00
常用的数据库访问方式是什么?
2009-11-01 15:08:00
oracle初始化参数设置
2010-07-31 12:47:00
详解python播放音频的三种方法
2021-12-16 09:19:11
提醒各位一下,IE透明会失效的
2009-03-31 12:48:00
![](https://img.aspxhome.com/file/UploadPic/20093/31/icon_lol-37s.gif)
PHP封装的一个支持HTML、JS、PHP重定向的多功能跳转函数
2023-11-19 07:25:14
Python读取stdin方法实例
2022-09-07 19:03:00
![](https://img.aspxhome.com/file/2023/9/86159_0s.png)
Python基础之教你怎么在M1系统上使用pandas
2023-09-02 12:56:23
![](https://img.aspxhome.com/file/2023/1/82921_0s.png)
Golang优雅保持main函数不退出的办法
2023-07-12 21:15:54
document.execCommand() 解析
2007-11-13 17:22:00
Python Vaex实现快速分析100G大数据量
2021-05-24 08:48:58
![](https://img.aspxhome.com/file/2023/8/80538_0s.png)
windows及linux环境下永久修改pip镜像源的方法
2021-02-19 09:08:59
![](https://img.aspxhome.com/file/2023/3/86473_0s.jpg)
Python while、for、生成器、列表推导等语句的执行效率测试
2021-03-05 02:17:54
python根据京东商品url获取产品价格
2022-01-26 12:14:31
以PHP代码为实例详解RabbitMQ消息队列中间件的6种模式
2023-06-08 12:15:53
![](https://img.aspxhome.com/file/2023/2/55492_0s.png)
保护SQL服务器的安全 用户识别问题
2008-12-24 15:26:00
![](https://img.aspxhome.com/file/UploadPic/200812/20081225122629996.jpg)