Python Design Patterns 简明教程

Python Design Patterns - Queues

队列是一组对象,它定义一个遵循 FIFO(快速进先出)和 LIFO(后进先出)程序的简单数据结构。插入和删除操作分别称为 enqueuedequeue 操作。

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

How to implement the FIFO procedure?

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

Output

上述程序生成以下输出 −

fifo

How to implement the LIFO procedure?

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

Output

上述程序生成以下输出 −

lifo

What is a Priority Queue?

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

How to implement a priority queue?

优先级队列的实现如下−

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

Output

上述程序生成以下输出 −

priority queues