Python设计模式 专题
您的位置:python > Python设计模式专题 > 队列
队列
作者:--    发布时间:2019-11-20

队列是对象的集合,它定义了fifo(先进先出)和lifo(后进先出)过程之后的简单数据结构。 插入和删除操作被称为入队和出队操作。

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

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

执行上述程序生成以下输出 -

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

执行上述程序生成以下输出 -

什么是优先级队列?

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

如何实现优先队列?

优先队列的实现如下 -

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

执行上述程序生成以下输出 -


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册