以给定的优先级对元素进行排序,每次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//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'))
[[, , ], [, , ], [, , ]]
[[, , ], [, , ]]
[[, , ]]
[] 进程已结束,退出代码0

最新文章

  1. 利用Python进行数据分析(7) pandas基础: Series和DataFrame的简单介绍
  2. 使用iScroll时,input等不能输入内容的解决方法(share)
  3. 谈PHP中信息加密技术
  4. Web service是什么?(转)
  5. bitmap缩放时抗锯齿
  6. NFC(3)Android上的NFC,开启NFC,3种NDEF数据
  7. ubuntu下使用vi是方向键变乱码 退格键不能使用的解决方法
  8. Security log is full,only administrator can log on to fix the problem(安全日志满了)
  9. python 数据类型(列表)学习笔记
  10. 二分图的判定hihocoder1121 and hdu3478
  11. 红帽(Red Hat Linux)下SVN服务器的安装与配置
  12. treeview树形菜单,递归
  13. FPGA笔记-阅读.dat文件
  14. Qt 学习之路 2(84):Repeater
  15. CSS3中选择器
  16. HTML学习笔记四
  17. w3wp.exe已附加有调试器,但没有该调试器配置为调试此未经处理的异常,若要调试此异常,必须分离当前的调试器。
  18. My Go Resolutions for 2017(from Russ cox's blog)
  19. Uva - 1589 - Xiangqi
  20. webstorm快速输入标签

热门文章

  1. 简单的并发服务器(多个线程各自accept)
  2. [DeeplearningAI笔记]序列模型3.3集束搜索
  3. Lucene 索引与检索架构图
  4. CSS 定位相关属性 :position
  5. 【转】ubuntu 11.04使用apt-get安装软件时一直提示E:unable to locate package
  6. 覆盖equals时总要覆盖hashCode
  7. 认识单点登录cas
  8. hash(2018年CSUST省赛选拔赛第一场B题+hash+字典树)
  9. HDU 1394 Minimum Inversion Number (树状数组)
  10. Tornado/Python 学习笔记(一)