Python 設計模式 - 佇列



佇列是一種物件集合,它定義了一種簡單的遵循FIFO(先進先出)和LIFO(後進先出)原則的資料結構。插入和刪除操作分別稱為入隊出隊操作。

佇列不允許隨機訪問其包含的物件。

如何實現FIFO原則?

以下程式有助於實現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原則?

以下程式有助於實現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
廣告