隊(duì)列是對(duì)象的集合,它定義了FIFO(先進(jìn)先出)和LIFO(后進(jìn)先出)過(guò)程之后的簡(jiǎn)單數(shù)據(jù)結(jié)構(gòu)。 插入和刪除操作被稱為入隊(duì)和出隊(duì)操作。
隊(duì)列不允許隨機(jī)訪問(wèn)它們包含的對(duì)象。
以下程序演示如何實(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í)現(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ì)列是一個(gè)容器數(shù)據(jù)結(jié)構(gòu),它使用有序鍵管理一組記錄,以提供對(duì)指定數(shù)據(jù)結(jié)構(gòu)中具有最小或最大鍵的記錄的快速訪問(wèn)。
優(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í)行上述程序生成以下輸出 -