queue使用示例

1、queue的简单使用

示例代码如下(queueTest1.py):

#! /usr/bin/env python
#-*- coding:utf-8 -*-

from Queue import Queue

q = Queue()
for i in range(5):
    q.put(i)

q.put((1,2,3))
while not q.empty():
    print q.get(),

运行效果如下:

$ python queueTest1.py
0 1 2 3 4 (1, 2, 3)

该代码的github地址: https://github.com/mike-zhang/pyExamples/blob/master/dataStructure/queue_examples/queueTest1.py

2、LifoQueue的简单使用

示例代码如下(lifoqueueTest1.py):

#! /usr/bin/env pyton
#-*- coding:utf-8 -*-

from Queue import LifoQueue

q = LifoQueue()
print "put :",
for i in range(5):
    print i,
    q.put(i)

print "\nget :",
while not q.empty():
    print q.get(),

运行效果如下:

$ python lifoqueueTest1.py
put : 0 1 2 3 4
get : 4 3 2 1 0

该代码的github地址: https://github.com/mike-zhang/pyExamples/blob/master/dataStructure/queue_examples/lifoqueueTest1.py

3、 PriorityQueue的简单使用

示例代码如下(priorityqueueTest1.py):

#! /usr/bin/env python
#-*- coding:utf-8 -*-

from Queue import PriorityQueue

class MyPriorityQueue(PriorityQueue):
    def __init__(self):
        PriorityQueue.__init__(self)
        self.counter = 0
    def put(self,item,priority):
        PriorityQueue.put(self,(priority,self.counter,item))
        self.counter += 1

    def get(self,*args,**kwargs):
        _,_,item = PriorityQueue.get(self,*args,**kwargs)
        return item

q = MyPriorityQueue()
q.put("item1",2)
q.put("item2",1)

while not q.empty():
    print q.get()

运行效果如下:

$ python priorityqueueTest1.py
item2
item1

该代码的github地址: https://github.com/mike-zhang/pyExamples/blob/master/dataStructure/queue_examples/priorityqueueTest1.py