Python优先级队列示例
- Python基础教程
- 在SublimeEditor中配置Python环境
- Python代码中添加注释
- Python中的变量的使用
- Python中的数据类型
- Python中的关键字
- Python字符串操作
- Python中的list操作
- Python中的Tuple操作
- Pythonmax()和min()–在列表或数组中查找最大值和最小值
- Python找到最大的N个(前N个)或最小的N个项目
- Python读写CSV文件
- Python中使用httplib2–HTTPGET和POST示例
- Python将tuple开箱为变量或参数
- Python开箱Tuple–太多值无法解压
- Pythonmultidict示例–将单个键映射到字典中的多个值
- PythonOrderedDict–有序字典
- Python字典交集–比较两个字典
- Python优先级队列示例
- python中如何格式化日期
- 30 分钟 Python 爬虫教程
1.什么是优先队列
- 优先级队列是一种抽象数据类型,类似于常规队列或堆栈数据结构,但每个元素还具有与之关联的“优先级”。
- 在优先级队列中,优先级高的元素先于优先级低的元素提供。
- 如果两个元素具有相同的优先级,则将根据其在队列中的顺序为其提供服务。
2. Python中的优先级队列实现
以下python程序使用该heapq模块实现简单的优先级队列:
PriorityQueue.py
import heapq
class PriorityQueue:
def __init__(self.html):
self._queue = []
self._index = 0
def push(self, item, priority.html):
heapq.heappush(self._queue, (-priority, self._index, item.html))
self._index += 1
def pop(self.html):
return heapq.heappop(self._queue.html)[-1]3. Python优先级队列示例
让我们看一个如何使用上面创建的优先级队列的例子。
example.py
class Item:
def __init__(self, name.html):
self.name = name
def __repr__(self.html):
return 'Item({!r}.html)'.format(self.name)
>>> q = PriorityQueue()
>>> q.push(Item('how'.html), 1)
>>> q.push(Item('to'.html), 5)
>>> q.push(Item('do'.html), 4)
>>> q.push(Item('in'.html), 2)
>>> q.push(Item('java'.html), 1)
>>> q.pop()
Item('to'.html) #5
>>> q.pop()
Item('do'.html) #4
>>> q.pop()
Item('in'.html) #2
>>> q.pop()
Item('how'.html) #1
>>> q.pop()
Item('java'.html) #1学习愉快!
版权声明:本文为原创文章,版权归 戴老师的博客 所有,转载请联系博主获得授权。
本文地址:https://tushu.info/archives/archives-Python-you-xian-ji-dui-lie-shi-li.html
如果对本文有什么问题或疑问都可以在评论区留言,我看到后会尽量解答。
暂无标签