队列是对象的集合,它定义了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程序 -
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
执行上述程序生成以下输出 -