有个需求,要接收不定时的一系列重复的消息,但是不想要旧的,只想保存最新收到的消息,双边队列完美完美解决,自动把旧的消息释放,最终还能很方便的取出最新的消息,demo如下,你试试就知道香在哪了!
from collections import deque
test_l = [1,2,3,4,5,6,7,8]
test_q = deque(maxlen=5)
for item in test_l:
test_q.append(item)
print(test_q.__len__())
print(test_q)
print(test_q.pop())
print(test_q.popleft())
test_q.append(9)
print(test_q)
--------------------------------------------------
5
deque([4, 5, 6, 7, 8], maxlen=5)
8
4
deque([5, 6, 7, 9], maxlen=5)