• 使用deque保留有限的记录


    # 使用deque保留有限的记录
    >>> from collections import deque
    >>> q = deque(maxlen=3) # 指定队列的最大长度,若不指定,则长度不限
    >>> q.append(1)
    >>> q
    deque([1], maxlen=3)
    >>> q.append(2)
    >>> q
    deque([1, 2], maxlen=3)
    >>> q.append(3)
    >>> q
    deque([1, 2, 3], maxlen=3)
    >>> q.append(4)
    >>> q
    deque([2, 3, 4], maxlen=3) 
    # 超过最大长度后继续在末尾添加元素会自动将最前面一个元素挤走
    >>> q.appendleft(5) # 在队列的开头位置添加元素
    >>> q
    deque([5, 2, 3], maxlen=3) 
    # 超过最大长度后继续在开头添加元素会自动将最后面一个元素挤走
    >>> q.pop()          # 弹出最后一个元素
    3
    >>> q
    deque([5, 2], maxlen=3)
    >>> q.popleft()     # 弹出第一个元素
    5
    >>> q
    deque([2], maxlen=3)
    # 使用队列比使用列表的速度更快

    参考资料:
      Python Cookbook, 3rd edition, by David Beazley and Brian K. Jones (O’Reilly).

  • 相关阅读:
    Vue Bug
    Vue.js(一)
    Node.js简介
    对请求链接的URLEncode处理
    淘宝开放平台
    Java基础(一)
    计算机基础知识
    Unity中对象池的使用
    希尔排序算法
    插入排序算法
  • 原文地址:https://www.cnblogs.com/hycstar/p/9324382.html
Copyright © 2020-2023  润新知