使用deque保留有限的记录

Posted hycstar

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用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).

以上是关于使用deque保留有限的记录的主要内容,如果未能解决你的问题,请参考以下文章