Python3 队列

collections.deque

deque提供了popleftappendleft等函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from collections import deque

q = deque([1, 2, 3])

len(q) # 3

q.append(1) # deque([1, 2, 3, 1])

q.appendleft(4) # deque([4, 1, 2, 3, 1])

right = q.pop() # right == 1, q == deque([4, 1, 2, 3])

left = q.popleft() # left == 4, q == deque([1, 2, 3])

q.extend([9, 8]) # q == deque([1, 2, 3, 9, 8])

q.extendleft([1, 2]) # q == deque([2, 1, 1, 2, 3, 9, 8]) 这里注意被extend的list是倒序插入的

q.count(1) # 2

q.index(3) # 4

q.insert(1, 5) # q == deque([2, 5, 1, 1, 2, 3, 9, 8]) 指定索引插入元素

q.remove(1) # q == deque([2, 5, 1, 2, 3, 9, 8]) 移除第一个匹配的元素

q.reverse() # q == deque([8, 9, 3, 2, 1, 5, 2])

q.rotate() # q == deque([2, 8, 9, 3, 2, 1, 5])

q.rotate(3) # q == deque([2, 1, 5, 2, 8, 9, 3]) 将结尾三个元素旋转至开始