开发手册 欢迎您!
软件开发者资料库

Python设计模式 - 队列

Python设计模式队列 - 从简单和简单的步骤学习Python设计模式从基本到高级概念,包括简介,Python的Gist,模型视图控制器,单例,工厂,构建器,原型,外观,命令,适配器,装饰器,代理,责任链,观察员,状态,战略,模板,飞重,抽象工厂,面向对象的模式,面向对象的概念实施,迭代器模式,词典,列表数据结构,集,队列,字符串和序列化,Python中的并发,反模式, 异常处理。

队列是一组对象,它们定义了FIFO(快速输入)和LIFO(后进先出)过程之后的简单数据结构.插入和删除操作称为 enqueue 出列操作.

队列不允许随机访问它们包含的对象.

如何实现FIFO程序?

以下程序有助于实现FIFO :

import Queueq = Queue.Queue()#put items at the end of the queuefor x in range(4):   q.put("item-" + str(x))#remove items from the head of the queuewhile not q.empty():   print q.get()

输出

上述程序生成以下输出 :

Fifo

如何实施LIFO程序?

以下程序有助于实施LIFO程序 :

import Queueq = Queue.LifoQueue()#add items at the head of the queuefor x in range(4):   q.put("item-" + str(x))#remove items from the head of the queuewhile not q.empty():   print q.get()

输出

上述程序生成以下输出 :

Lifo

什么是优先级队列?

优先级队列是一个容器数据结构,用于管理一组记录有序键,用于快速访问指定数据结构中具有最小或最大键的记录.

如何实现优先级队列?

优先级队列的实现如下 :

import Queueclass 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

输出

上述程序生成以下输出 :

Priority Queues