Python队列(Queue)

Python队列(Queue) 首页 / 数据结构入门教程 / Python队列(Queue)

队列(Queue)就跟现实中排队买车票一下,第一个到的排前面,后面到的排在最后,可以使用python列表实现队列,无涯教程​​可以在其中使用insertpop方法添加和删除元素。

添加元素

在下面的示例中,创建一个队列类,在其中实现了先进先出方法,使用内置的insert方法添加数据元素。

class Queue:

  def __init__(self):
      self.queue=list()

  def addtoq(self,dataval):
# 插入方法添加元素
      if dataval not in self.queue:
          self.queue.insert(0,dataval)
          return True
      return False

  def size(self):
      return len(self.queue)

TheQueue=Queue()
TheQueue.addtoq("Mon")
TheQueue.addtoq("Tue")
TheQueue.addtoq("Wed")
print(TheQueue.size())

执行以上代码后,将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/python-data-structure/python-queue.html

来源:LearnFk无涯教程网

3

删除元素

在下面的示例中,无涯教程创建一个队列类,在其中插入数据,然后使用内置的pop方法删除数据。

class Queue:

  def __init__(self):
      self.queue=list()

  def addtoq(self,dataval):
# insert方法添加元素
      if dataval not in self.queue:
          self.queue.insert(0,dataval)
          return True
      return False
# pop方法移除元素
  def removefromq(self):
      if len(self.queue)>0:
          return self.queue.pop()
      return ("No elements in Queue!")

TheQueue=Queue()
TheQueue.addtoq("Mon")
TheQueue.addtoq("Tue")
TheQueue.addtoq("Wed")
print(TheQueue.removefromq())
print(TheQueue.removefromq())

执行以上代码后,将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/python-data-structure/python-queue.html

来源:LearnFk无涯教程网

Mon
Tue

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

前端全链路优化实战课 -〔唐俊开〕

快速上手C++数据结构与算法 -〔王健伟〕

李智慧 · 高并发架构实战课 -〔李智慧〕

郭东白的架构课 -〔郭东白〕

Spring编程常见错误50例 -〔傅健〕

Spark核心原理与实战 -〔王磊〕

爱上跑步 -〔钱亮〕

零基础学Python -〔尹会生〕

朱赟的技术管理课 -〔朱赟〕

好记忆不如烂笔头。留下您的足迹吧 :)