Python设计模式 队列


队列是对象的集合,它定义了遵循 FIFO(快进快出)和 LIFO(后进先出)过程的简单数据结构。插入和删除操作称为 enqueue and dequeue 操作。

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

如何实现先进先出程序?


以下程序有助于实现 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()

上述程序产生如下输出:

Fifo

如何实施后进先出程序?


以下程序有助于执行 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()

上述程序产生如下输出:

Lifo

什么是优先队列?


优先级队列是一种容器数据结构,它管理具有有序键的一组记录,以提供对指定数据结构中键最小或最大的记录的快速访问。

如何实现优先级队列?

优先队列的实现如下:

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

上述程序产生如下输出:

Priority Queues