Python双端队列

这个双端队列,我觉得只是对python可迭代对象的一个扩展。

如果想要对可迭代对象有更好的操作,可以使用这个类

导入

from collections import deque

创建对象

不初始化队列

dq = deque(可迭代对象,队列长度)

初始化队列

dq = deque(可迭代对象,队列长度)

此队列可以使用任何列表的操作,只要列表可以的操作,此队列都可以使用

from collections import deque

dq = deque([1,2,3,4,5])

res = dq.pop()
print(res)
res = dq.popleft()
print(res)

结果:  5
       1

由此得到,默认的pop是从右往左的。

那么appendleft方法和append也是一样,append默认由右边开始添加,appendleft则是从左边开始添加。

rotate方法
from collections import deque

dq = deque([1,2,3,4,5])

dq.rotate(3)

res  = list(map(lambda x:x, dq))
print(res)
结果:[3, 4, 5, 1, 2]

由此可见,rotate方法设置3,将会把队列最后一个元素依次移动到队列的第一位

其他方法于列表操作一样,这里不再赘述

猜你喜欢

转载自blog.csdn.net/qq_38949193/article/details/81254719