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对比