Python队列的定义与使用方法示例

yipeiwu_com5年前Python基础

本文实例讲述了Python队列的定义与使用方法。分享给大家供大家参考,具体如下:

虽然Python有自己的队列模块,我们只需要在使用时引入该模块就行,但是为了更好的理解队列,自己将队列实现了一下。

队列是一种数据结构,它的特点是先进先出,也就是说队尾添加一个元素,队头移除一个元素,类似于商场排队结账,先来的人先接账,后来的排在队尾。在我们日常生活中,发送短信就会用到队列。下面是Python实现队列的代码:

#!/usr/bin/python
#coding=utf-8
class Queue(object) :
 def __init__(self, size) :
  self.size = size
  self.queue = []
 def __str__(self) :
  return str(self.queue)
 #获取队列的当前长度
 def getSize(self) :
  return len(self.quene)
 #入队,如果队列满了返回-1或抛出异常,否则将元素插入队列尾
 def enqueue(self, items) :
  if self.isfull() :
   return -1
   #raise Exception("Queue is full")
  self.queue.append(items)
 #出队,如果队列空了返回-1或抛出异常,否则返回队列头元素并将其从队列中移除
 def dequeue(self) :
  if self.isempty() :
   return -1
   #raise Exception("Queue is empty")
  firstElement = self.queue[0]
  self.queue.remove(firstElement)
  return firstElement
 #判断队列满
 def isfull(self) :
  if len(self.queue) == self.size :
   return True
  return False
 #判断队列空
 def isempty(self) :
  if len(self.queue) == 0 :
   return True
  return False

下面是该队列类.py文件的测试代码:

if __name__ == '__main__' :
 queueTest = Queue(10)
 for i in range(10) :
  queueTest.enqueue(i)
 print queueTest.isfull()
 print queueTest
 print queueTest.getSize()
 for i in range(5) :
  print queueTest.dequeue()
 print queueTest.isempty()
 print queueTest
 print queueTest.getSize()

测试结果:

更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python实现日常记账本小程序

python实现收支的自动计算,能够查询每笔账款的消费详情,具体内容如下 1、函数需要两个文件:一个类似钱包功能,存放钱;另一个用于记录每笔花销的用途 #!/usr/bin/env...

Python安装Imaging报错:The _imaging C module is not installed问题解决方法

今天写Python程序上传图片需要用到PIL库,于是到http://www.pythonware.com/products/pil/#pil117下载了一个1.1.7版本的,我用的是Ce...

Python实现监控程序执行时间并将其写入日志的方法

本文实例讲述了Python实现监控程序执行时间并将其写入日志的方法。分享给大家供大家参考。具体实现方法如下: # /usr/bin/python # -*- coding:utf-8...

python 读写txt文件 json文件的实现方法

首先第一步,打开文件,有两个函数可供选择:open() 和  file() ①. f = open('file.txt',‘w')    ... &nbs...

numpy数组之存取文件的实现示例

将 numpy 数组存入文件,有多种文件类型可供选择,对应地就有不同的方法来读写。 下面我将介绍读写 numpy 的三类文件: txt 或者 csv 文件 npy 或者 npz...