- Python 设计模式教程
- Python 设计模式 - 主页
- 介绍
- Python 设计模式 - 要点
- 模型视图控制器模式
- Python 设计模式 - 单例
- Python 设计模式 - 工厂
- Python 设计模式 - 构建器
- Python 设计模式 - 原型
- Python 设计模式 - 外观
- Python 设计模式 - 命令
- Python 设计模式 - 适配器
- Python 设计模式 - 装饰器
- Python 设计模式 - 代理
- 责任链模式
- Python 设计模式 - 观察者
- Python 设计模式 - 状态
- Python 设计模式 - 策略
- Python 设计模式 - 模板
- Python 设计模式 - 享元
- 抽象工厂
- 面向对象
- 面向对象的概念实现
- Python 设计模式 - 迭代器
- 词典
- 列表数据结构
- Python 设计模式 - 集
- Python 设计模式 - 队列
- 字符串和序列化
- Python 中的并发
- Python 设计模式 - 反
- 异常处理
- Python 设计模式资源
- 快速指南
- Python 设计模式 - 资源
- 讨论
Python 设计模式 - 队列
队列是对象的集合,它定义了遵循 FIFO(快进快出)和 LIFO(后进先出)过程的简单数据结构。插入和删除操作称为入队和出队操作。
队列不允许随机访问它们包含的对象。
如何实现先进先出的程序?
以下程序有助于 FIFO 的实施 -
import Queue
q = Queue.Queue()
#put items at the end of the queue
for x in range(4):
q.put("item-" + str(x))
#remove items from the head of the queue
while not q.empty():
print q.get()
输出
上述程序生成以下输出 -
如何实施 LIFO 程序?
以下程序有助于实施 LIFO 程序 -
import Queue
q = Queue.LifoQueue()
#add items at the head of the queue
for x in range(4):
q.put("item-" + str(x))
#remove items from the head of the queue
while not q.empty():
print q.get()
输出
上述程序生成以下输出 -
什么是优先队列?
优先级队列是一种容器数据结构,它管理一组具有有序键的记录,以提供对指定数据结构中具有最小或最大键的记录的快速访问。
如何实现优先级队列?
优先级队列的实现如下 -
import Queue
class Task(object):
def __init__(self, priority, name):
self.priority = priority
self.name = name
def __cmp__(self, other):
return cmp(self.priority, other.priority)
q = Queue.PriorityQueue()
q.put( Task(100, 'a not agent task') )
q.put( Task(5, 'a highly agent task') )
q.put( Task(10, 'an important task') )
while not q.empty():
cur_task = q.get()
print 'process task:', cur_task.name
输出
上述程序生成以下输出 -
