It is also possible to use a list as a queue, where the first element added is the first element retrieved (``first-in, first-out''); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).
你也可以把链表当做队列使用,队列作为特定的数据结构,最先进入的元素最先 释放(先进先出)。不过,列表这样用效率不高。相对来说从列表末尾添加和弹 出很快;在头部插入和弹出很慢(因为,为了一个元素,要移动整个列表中的所 有元素)。
To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends.
要实现队列,使用 collections.deque ,它为在首尾两端快速插入和删除而设计。
For example:
>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")
# Terry arrives
>>> queue.append("Graham")
# Graham arrives
>>> queue.popleft()
# The first to arrive now leaves
'Eric'
>>> queue.popleft()
# The second to arrive now leaves
'John'
>>> queue
# Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])