隊(duì)列一個(gè)重要的數(shù)據(jù)結(jié)構(gòu),也比較簡(jiǎn)單。python內(nèi)置了隊(duì)列的實(shí)現(xiàn),十分好用,
下面就是一些例子:
import Queue
q = Queue.Queue() #普通隊(duì)列
for i in range(5):
q.put(i)
while not q.empty():
print q.get()
后進(jìn)先出隊(duì)列,這個(gè)有點(diǎn)像棧,也可以當(dāng)作棧來(lái)用。
q = Queue.LifoQueue()
for i in range(5):
q.put(i)
while not q.empty():
print q.get()
優(yōu)先隊(duì)列,可以給隊(duì)列里的元素設(shè)置優(yōu)先級(jí),彈出時(shí)優(yōu)先級(jí)高的先彈出。
q = Queue.PriorityQueue()
q.put([2,'hello'])
q.put([4,'good'])
print q.get()
class Job():
def __init__(self,describe,priority):
self.describe = describe
self.priority = priority
def __cmp__(self, other):
return cmp(self.priority,other.priority)
q1 = Queue.PriorityQueue(0)
q1.put( Job(3, 'Mid-level job'))#也可以傳入對(duì)象
q1.put( Job(10, 'Low-level job'))
q1.put( Job(1, 'Important job'))
print q1.get().describe