python collections deque_详解Python的collections模块中的deque双端队列结构

import collections

import threading

import time

candle = collections.deque(xrange(5))

def burn(direction, nextSource):

while True:

try:

next = nextSource()

except IndexError:

break

else:

print '%8s: %s' % (direction, next)

time.sleep(0.1)

print '%8s done' % direction

return

left = threading.Thread(target=burn, args=('Left', candle.popleft))

right = threading.Thread(target=burn, args=('Right', candle.pop))

left.start()

right.start()

left.join()

right.join()

线程交替处理两端,删除元素,知道这个deque为空。

Left: 0 Right: 4

Right: 3 Left: 1

Right: 2 Left done

Right done

旋转deque另外一个作用可以按照任意一个方向旋转,而跳过一些元素。

import collections

d = collections.deque(xrange(10))

print 'Normal:', d

d= collections.deque(xrange(10))

d.rotate(2)

print 'Right roration:', d

d = collections.deque(xrange(10))

d.rotate(-2)

print 'Left roration:', d

结果:

Normal: deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

Right roration: deque([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])

Left roration: deque([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])

再举个例子:

# -*- 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)

输出结果:

相关文章

相关视频

网友评论

文明上网理性发言,请遵守 新闻评论服务协议我要评论

立即提交

专题推荐独孤九贱-php全栈开发教程

全栈 100W+

主讲:Peter-Zhu 轻松幽默、简短易学,非常适合PHP学习入门

玉女心经-web前端开发教程

入门 50W+

主讲:灭绝师太 由浅入深、明快简洁,非常适合前端学习入门

天龙八部-实战开发教程

实战 80W+

主讲:西门大官人 思路清晰、严谨规范,适合有一定web编程基础学习

php中文网:公益在线php培训,帮助PHP学习者快速成长!

Copyright 2014-2020 https://www.php.cn/ All Rights Reserved | 苏ICP备2020058653号-1

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值