Python 数据结构之队列的实现
作者:lqh 时间:2021-11-28 15:27:26
Python 队列
Queue 队列是一种先进先出(FIFO)的数据类型, 新的元素通过 入队 的方式添加进 Queue 的末尾, 出队 就是从 Queue 的头部删除元素.
用列表来做 Queue:
queue = [] # 初始化一个列表数据类型对象, 作为一个队列
def enQ(): # 定义一个入栈方法
queue.append(raw_input('Enter New String: ').strip())
# 提示输入一个入队的 String 对象, 调用 Str.strip() 保证输入的 String 值不包含多余的空格
def deQ(): # 定义一个出队方法
if len(queue) == 0:
print "Cannot pop from an empty queue!"
else:
print 'Remove [', `queue.pop(0)`, ']'
# 使用反单引号(` `)来代替 repr(), 把 String 的值用引号扩起来, 而不仅显示 String 的值
# queue.pop(0) 总是将在队列中最前面的元素弹出
def viewQ(): # 定义一个显示队列中的内容的方法
print queue
CMDs = {'u':enQ, 'o':deQ, 'v':viewQ}
# 定义一个 Dict 类型对象, 将字符映射到相应的 function .可以通过输入字符来执行相应的操作
def showmenu(): # 定义一个操作菜单提示方法
pr = """
(E)nqueue
(D)equeue
(V)iew
(Q)uit
Enter choice: """
while True:
while True:
try:
choice = raw_input(pr).strip()[0].lower()
# Str.strip() 去除 String 对象前后的多余空格
# Str.lower() 将多有输入转化为小写, 便于后期的统一判断
# 输入 ^D(EOF, 产生一个 EOFError 异常)
# 输入 ^C(中断退出, 产生一个 keyboardInterrupt 异常)
except (EOFError, KeyboardInterrupt, IndexError):
choice = 'q'
print '\nYou picked: [%s]' % choice
if choice not in 'uovq':
print 'Invalid option, try again'
else:
break
if choice == 'q':
break
CMDs[choice]()
# 获取 Dict 中字符对应的 functionName, 实现函数调用
if __name__ == '__main__':
showmenu()
队列和堆栈的实现方式很相似, 区别在于队列总是先弹出第一个元素而堆栈总是先弹出最后一个元素.
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
来源:http://blog.csdn.net/jmilk/article/details/52371065
标签:Python,队列
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
浅谈Python中文件夹和python package包的区别
2021-03-23 21:57:26
![](https://img.aspxhome.com/file/2023/6/64326_0s.jpg)
详解python ThreadPoolExecutor异常捕获
2023-08-09 12:54:30
基于Python的ModbusTCP客户端实现详解
2022-02-03 10:54:25
![](https://img.aspxhome.com/file/2023/1/115721_0s.jpg)
asp开发中textarea常见问题
2008-04-13 06:34:00
Perl下应当如何连接Access数据库
2008-12-04 13:06:00
Python random库使用方法及异常处理方案
2023-10-07 13:43:46
![](https://img.aspxhome.com/file/2023/1/82701_0s.jpg)
DW MX新功能试用:嵌套模板
2008-02-03 11:35:00
![](https://img.aspxhome.com/file/UploadPic/20072/200723113533349s.jpg)
python学习之基于Python的人脸识别技术学习
2021-04-23 22:09:25
Python+Appium新手教程
2022-12-01 04:12:44
![](https://img.aspxhome.com/file/2023/4/77904_0s.png)
Python 正则表达式入门(初级篇)
2021-12-03 23:41:12
Python爬虫框架-scrapy的使用
2022-09-11 20:12:28
![](https://img.aspxhome.com/file/2023/7/95327_0s.png)
python实现网站用户名密码自动登录功能
2021-07-05 09:48:13
Oracle性能究极优化 下
2010-07-30 13:25:00
Python实现的简单hangman游戏实例
2021-04-11 19:26:47
Python使用正则匹配实现抓图代码分享
2021-09-06 10:47:28
解决安装python库时windows error5 报错的问题
2022-06-14 05:26:04
flask上传作品之dbm操作的实现
2022-06-29 15:25:41
![](https://img.aspxhome.com/file/2023/1/94071_0s.png)
Python使用asyncio异步时的常见问题总结
2021-02-06 04:43:12
Pycharm取消py脚本中SQL识别的方法
2023-10-30 16:23:13
![](https://img.aspxhome.com/file/2023/0/92060_0s.jpg)
Python的logging模块基本用法
2021-01-06 07:39:52