5.1.2. 列表作为队列使用

列表也可以用作队列,其中先添加的元素被最先取出 (“先进先出”);然而列表用作这个目的相当低效。因为在列表的末尾添加和弹出元素非常快,但是在列表的开头插入或弹出元素却很慢 (因为所有的其他元素都必须移动一位)。

若要实现一个队列, collections.deque 被设计用于快速地从两端操作。例如

  1. >>> from collections import deque
  2. >>> queue = deque(["Eric", "John", "Michael"])
  3. >>> queue.append("Terry") # Terry arrives
  4. >>> queue.append("Graham") # Graham arrives
  5. >>> queue.popleft() # The first to arrive now leaves
  6. 'Eric'
  7. >>> queue.popleft() # The second to arrive now leaves
  8. 'John'
  9. >>> queue # Remaining queue in order of arrival
  10. deque(['Michael', 'Terry', 'Graham'])