队列是一组对象,它们定义了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()
输出
上述程序生成以下输出 :
如何实施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()
输出
上述程序生成以下输出 :
什么是优先级队列?
优先级队列是一个容器数据结构,用于管理一组记录有序键,用于快速访问指定数据结构中具有最小或最大键的记录.
如何实现优先级队列?
优先级队列的实现如下 :
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
输出
上述程序生成以下输出 :