目录

Python Design Patterns - Queues

队列是一组对象,它们定义了FIFO(快速输入快速)和LIFO(后进先出)过程之后的简单数据结构。 插入和删除操作称为enqueuedequeue操作。

队列不允许随机访问它们包含的对象。

如何实现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()

输出 (Output)

上述程序生成以下输出 -

FIFO

如何实施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()

输出 (Output)

上述程序生成以下输出 -

后进先出法

什么是优先级队列?

优先级队列是一种容器数据结构,它使用有序键管理一组记录,以便快速访问具有指定数据结构中最小或最大键的记录。

如何实现优先级队列?

优先队列的实现如下 -

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

输出 (Output)

上述程序生成以下输出 -

优先级队列
↑回到顶部↑
WIKI教程 @2018