美文网首页
Python CookBook 笔记 | deque

Python CookBook 笔记 | deque

作者: 大师的学徒 | 来源:发表于2020-03-12 11:52 被阅读0次
from collections import deque

q = deque(maxlen = 3)
q.append(1)
q.append(2)
q.append(0)

deque(maxlen = n) 创建一个固定长度的队列,当有新的数据加入队列会自动移除最早的数据

>>> q
deque([1, 2, 0], maxlen=3)

添加元素到队列尾端

>>> q.append(2)
>>> q
deque([2, 0, 2], maxlen=3)

添加元素到队首

>>> q.appendleft(5)
>>> q
deque([5, 2, 0], maxlen=3)

=======================================================
deque可以协助在简单队列的两端执行添加和弹出任务,如:

from collections import deque

q = deque()
q.append(2)
q.append(5)
q.append(4)

一些在列表里没有的命令,如 popleft() 和 appendleft()

>>> q
deque([2, 5, 4])
>>> q.appendleft(333)
>>> q
deque([333, 2, 5, 4])
>>> q.pop()
4
>>> q
deque([333, 2, 5])
>>> q.popleft()
333

PS:用deque从两端添加或弹出的复杂度是O(1), 但是在list中插入或移除元素的复杂度为O(N),所以转化为deque会非常节省资源。

相关文章

网友评论

      本文标题:Python CookBook 笔记 | deque

      本文链接:https://www.haomeiwen.com/subject/cioyjhtx.html