python之把列表当做队列使用

把列表当做队列使用,只是在列表中第一个加入的元素,第一个提取出来,拿列表当做队列用,效率并不高。在列表中最后添加或者删除元素速度很快,然而从列表里插入或者从头弹出速度却不快,因为其他所有元素都要一个一个移动。

 1 from collections import deque 
 2 
 3 queue = deque(['Eric','John','Michael']) #定义队列
 4 
 5 queue.append('Terry') #将字符串Terry追加到队列末尾
 6 print(queue) #打印是否符合预期 deque(['Eric', 'John', 'Michael', 'Terry'])
 7 
 8 queue.append('Graham') #将Graham追加到队列末尾
 9 print(queue) #打印是否符合预期 deque(['Eric', 'John', 'Michael', 'Terry', 'Graham'])
10 
11 a = queue.popleft() #从队列中取出最左边的元素并赋值给变量a
12 print(a) #打印 Eric
13 print(queue) #打印队列 deque(['John', 'Michael', 'Terry', 'Graham'])
14 
15 b = queue.popleft() #再次从队列最左边取出元素并赋值给b
16 print(b) #打印John
17 print(queue) #再次打印队列 deque(['Michael', 'Terry', 'Graham'])

有些人觉得可能会用popright,会出错误,deque并无方法popright,要查看deque里有啥方法,可以打印下dir(deque)。