zoukankan      html  css  js  c++  java
  • python 栈和队列(使用list实现)

    5.1.1. Using Lists as 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)
    >>> stack
    [3, 4, 5, 6, 7]
    >>> stack.pop()
    7
    >>> stack
    [3, 4, 5, 6]
    >>> stack.pop()
    6
    >>> stack.pop()
    5
    >>> stack
    [3, 4]
    

    5.1.2. Using Lists as 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 deque
    >>> queue = deque(["Eric", "John", "Michael"])
    >>> queue.append("Terry")           # Terry arrives
    >>> queue.append("Graham")          # Graham arrives
    >>> queue.popleft()                 # The first to arrive now leaves
    'Eric'
    >>> queue.popleft()                 # The second to arrive now leaves
    'John'
    >>> queue                           # Remaining queue in order of arrival
    deque(['Michael', 'Terry', 'Graham'])
  • 相关阅读:
    Mock工具Mockito教程
    基于Jmeter的自动化测试实施方案
    基于敏捷的测试交付物通用设计
    Jmeter 冒烟测试设计
    Jmockit之mock特性详解
    Sonar 常用代码规则(二)
    从Hg迁移到Git
    使用谷歌colab训练crnn模型
    使用AIstudio训练YOLOv3模型
    阿里云服务器部署Djano+Nginx+uWSGI+conda+Https
  • 原文地址:https://www.cnblogs.com/yechanglv/p/6937999.html
Copyright © 2011-2022 走看看