Using Lists as Queues in Python----在Python中把链表当作队列使用

    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'])


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值