队列是一组对象,它们定义了FIFO(快速输入)和LIFO(后进先出)过程之后的简单数据结构.插入和删除操作称为 enqueue 和出列操作.
队列不允许随机访问它们包含的对象.
以下程序有助于实现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程序 :
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
上述程序生成以下输出 :