您的位置:首页 > 编程语言 > Python开发

Python - 实现Stacks 和Queues

2017-08-25 10:20 351 查看
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 : 7
print(stack)    #output : [3, 4, 5, 6]


用deque实现Stacks

from collections import deque

stack1 = deque([3, 4, 5])
stack1.append(6)
stack1.append(7)
print(stack1)   #output : deque([3, 4, 5, 6, 7])
stack1.pop()    #output : 7
print(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
4000
from both ends. For example:

from collections import deque

queue = deque([3, 4, 5])
queue.append(6)
queue.append(7)
print(queue)    #output : deque([3, 4, 5, 6, 7])
queue.popleft() #output : 3
print(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对比
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: