Python
来源:互联网 发布:网易公开课mac版 编辑:程序博客网 时间:2024/06/03 13:10
python没有像C++那样的struct 来实现栈 和队列,但是可以用deque来实现栈和队列,当然,栈也可以用最简单的list来实现。
实现 Stacks
- 用lists实现Stacks
The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index. For example:
stack = [3, 4, 5]stack.append(6)stack.append(7)print(stack) #output : [3, 4, 5, 6, 7]stack.pop() #output : 7print(stack) #output : [3, 4, 5, 6]
- 用deque实现Stacks
from collections import dequestack1 = deque([3, 4, 5])stack1.append(6)stack1.append(7)print(stack1) #output : deque([3, 4, 5, 6, 7])stack1.pop() #output : 7print(list(stack1)) #output : [3, 4, 5, 6]
实现 Queues
- 用deque实现Queues
It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).
To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:
from collections import dequequeue = deque([3, 4, 5])queue.append(6)queue.append(7)print(queue) #output : deque([3, 4, 5, 6, 7])queue.popleft() #output : 3print(list(queue)) #output : [4, 5, 6, 7]
- queue是多线程中的使用的栈,但是Python 解释器有一个全局解释器锁(PIL),导致每个 Python 进程中最多同时运行一个线程,因此 Python 多线程程序并不能改善程序性能,不能发挥多核系统的优势。
- multiprocessing.Queue是Python 2.6 引入的用来实现多进程的一种高性能栈。
- collections.deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈。
事实证明:collections.deque比前两种效率都高,可以参考高性能Python之:Queue,deque,queue对比
阅读全文
0 0
- Python
- Python
- Python
- python
- Python
- PYTHON
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- python
- Python
- Spark RDD基础操作
- 编译器与解释器的区别
- 安全的使用new分配内存
- mysql数据库设置远程连接权限
- hexo安装next主题的步骤
- Python
- Kylin报错classnotfound:org.apache.hadoop.hive.serde2.typeinfo.typeInfo
- Java垃圾回收机制
- 转载:管道通信总结
- html5中新增两个表单属性,分别autocomplete和novalidate属性
- jmeter 请求发送加密参数(其中包含Json嵌套)
- $.post()方法
- nginx安装以及注意事项
- 【USACO TRAINING】货币系统