python 列表之队列

列表实现队列操作(FIFO),可以使用标准库里的 collections.deque,deque是double-ended quene的缩写,双端队列的意思,它可以实现从队列头部快速增加和取出对象。

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

deque用rotate实现跑马灯操作,转自http://www.zlovezl.cn/articles/collections-in-python/

# -*- coding: utf-8 -*-
"""
下面这个是一个有趣的例子,主要使用了deque的rotate方法来实现了一个无限循环
的加载动画
"""
import sys
import time
from collections import deque

fancy_loading = deque('>--------------------')

while True:
    print '\r%s' % ''.join(fancy_loading),
    fancy_loading.rotate(1)
    sys.stdout.flush()
    time.sleep(0.08)

  

posted @ 2017-08-14 15:25  郭雪原  阅读(262)  评论(0编辑  收藏  举报