实现说明
循环只出现在 for event in ["boot", "login", "upload", "logout"],它的每次迭代处理一个元素。
顶层就这几处状态:recent、first、rotation。
使用要点
- 跑完文件,输出里会留下标记——
popped:、right :。
常见问题
运行之前需要装什么吗?
不需要——用到的每个 API 都随语言运行时自带,无需安装。 全部导入都来自标准库:collections。 文件的状态由几个模块级绑定持有:recent、first、rotation。
核心语句
for event in ["boot", "login", "upload", "logout"]:
recent.append(event)
print(list(recent))
代码示例
from collections import deque
# deque(maxlen=N):固定容量事件窗口,超限时最旧一端自动滑出
recent = deque(maxlen=3)
for event in ["boot", "login", "upload", "logout"]:
recent.append(event)
print(list(recent))
# 两端操作 O(1):popleft 不搬移整个列表
first = recent.popleft()
print("popped:", first, "| left:", list(recent))
# rotate(n):正数右移、负数左移,轮转调度的一等原语
rotation = deque([1, 2, 3, 4])
rotation.rotate(1)
print("right :", list(rotation))
rotation.rotate(-2)
print("left :", list(rotation))