
- Python 設計模式教程
- Python 設計模式 - 首頁
- 介紹
- Python 設計模式 - 要點
- 模型-檢視-控制器模式
- Python 設計模式 - 單例模式
- Python 設計模式 - 工廠模式
- Python 設計模式 - 建造者模式
- Python 設計模式 - 原型模式
- Python 設計模式 - 外觀模式
- Python 設計模式 - 命令模式
- Python 設計模式 - 介面卡模式
- Python 設計模式 - 裝飾器模式
- Python 設計模式 - 代理模式
- 責任鏈模式
- Python 設計模式 - 觀察者模式
- Python 設計模式 - 狀態模式
- Python 設計模式 - 策略模式
- Python 設計模式 - 模板模式
- Python 設計模式 - 享元模式
- 抽象工廠模式
- 面向物件
- 面向物件概念實現
- Python 設計模式 - 迭代器模式
- 字典
- 列表資料結構
- Python 設計模式 - 集合
- Python 設計模式 - 佇列
- 字串與序列化
- Python中的併發
- Python 設計模式 - 反模式
- 異常處理
- Python 設計模式資源
- 快速指南
- Python 設計模式 - 資源
- 討論
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()
輸出
上述程式生成以下輸出:

如何實現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()
輸出
上述程式生成以下輸出:

什麼是優先佇列?
優先佇列是一種容器資料結構,它管理一組具有有序鍵的記錄,以便快速訪問具有指定資料結構中最小或最大鍵的記錄。
如何實現優先佇列?
優先佇列的實現如下:
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
輸出
上述程式生成以下輸出:

廣告