鍍金池/ 教程/ Python/ 隊(duì)列
反模式
隊(duì)列
適配器設(shè)計(jì)模式
享元設(shè)計(jì)模式
Python設(shè)計(jì)模式
工廠模式
模板設(shè)計(jì)模式
構(gòu)建器(Builder)設(shè)計(jì)模式
Python設(shè)計(jì)模式概要
命令設(shè)計(jì)模式
Python設(shè)計(jì)模式簡(jiǎn)介
觀察者設(shè)計(jì)模式
代理設(shè)計(jì)模式
異常處理
責(zé)任鏈設(shè)計(jì)模式
字典實(shí)現(xiàn)
抽象工廠設(shè)計(jì)模式
Python并發(fā)(多線程)
策略設(shè)計(jì)模式
門面(Facade)設(shè)計(jì)模式
原型設(shè)計(jì)模式
迭代器設(shè)計(jì)模式
集合
單例模式
列表數(shù)據(jù)結(jié)構(gòu)
狀態(tài)設(shè)計(jì)模式
模型視圖控制器(MVC)模式
裝飾器設(shè)計(jì)模式
面向?qū)ο蟾拍畹膶?shí)現(xiàn)
面向?qū)ο笤O(shè)計(jì)模式
字符串和序列化

隊(duì)列

隊(duì)列是對(duì)象的集合,它定義了FIFO(先進(jìn)先出)和LIFO(后進(jìn)先出)過程之后的簡(jiǎn)單數(shù)據(jù)結(jié)構(gòu)。 插入和刪除操作被稱為入隊(duì)和出隊(duì)操作。

隊(duì)列不允許隨機(jī)訪問它們包含的對(duì)象。

如何實(shí)現(xiàn)FIFO程序?

以下程序演示如何實(shí)現(xiàn)先進(jìn)先出(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()

執(zhí)行上述程序生成以下輸出 -

如何實(shí)施LIFO程序?

以下程序如何實(shí)現(xiàn)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()

執(zhí)行上述程序生成以下輸出 -

什么是優(yōu)先級(jí)隊(duì)列?

優(yōu)先級(jí)隊(duì)列是一個(gè)容器數(shù)據(jù)結(jié)構(gòu),它使用有序鍵管理一組記錄,以提供對(duì)指定數(shù)據(jù)結(jié)構(gòu)中具有最小或最大鍵的記錄的快速訪問。

如何實(shí)現(xiàn)優(yōu)先隊(duì)列?

優(yōu)先隊(duì)列的實(shí)現(xiàn)如下 -

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

執(zhí)行上述程序生成以下輸出 -