实现优先级队列 --heapq模块
以给定的优先级对元素进行排序,每次pop删除优先级最高的
# coding=utf-8 # example.py # # Example of a priority queue import heapq class PriorityQueue: def __init__(self): self._queue = [] self._index = 0 def push(self, item, priority): heapq.heappush(self._queue, (-priority, self._index, item)) #在这里就是依据优先级的负数作排序依据,最小的在左边,是第0个值 self._index += 1 #当优先级一样是,index按照小的先输出,保证了先进先出 def pop(self): return heapq.heappop(self._queue)[-1] #返回item # Example use class Item: def __init__(self, name): self.name = name def __repr__(self): return 'Item({!r})'.format(self.name)#!后面可以加s r分别对应str() repr() ,和%用法类似,s没括号,r有括号 q = PriorityQueue() q.push(Item('foo'), 1) q.push(Item('bar'), 5) q.push(Item('spam'), 4) q.push(Item('grok'), 1) print("Should be bar:", q.pop()) print("Should be spam:", q.pop()) print("Should be foo:", q.pop()) print("Should be grok:", q.pop())
a=[5,8,9] b=[5,1,2] c=[4,6,7] ss=[] heapq.heappush(ss,a)#是按照a中序列的第一个作排序依据的 heapq.heappush(ss,b) heapq.heappush(ss,c) print ss s=heapq.heappop(ss)[-1] print s,ss s=heapq.heappop(ss)[-1] print s,ss s=heapq.heappop(ss)[-1] print s,ss
结果:

H:\Python27_64\python.exe H:/myfile/python-cookbook-master/src/1/implementing_a_priority_queue/example.py ('Should be bar:', Item('bar')) ('Should be spam:', Item('spam')) ('Should be foo:', Item('foo')) ('Should be grok:', Item('grok')) [[4, 6, 7], [5, 8, 9], [5, 1, 2]] 7 [[5, 1, 2], [5, 8, 9]] 2 [[5, 8, 9]] 9 [] 进程已结束,退出代码0
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!