详解Python的collections模块中的deque双端队列结构
作者:lucifercn 发布时间:2021-08-15 19:35:57
标签:Python,deque
deque 是 double-ended queue的缩写,类似于 list,不过提供了在两端插入和删除的操作。
appendleft 在列表左侧插入
popleft 弹出列表左侧的值
extendleft 在左侧扩展
例如:
queue = deque()
# append values to wait for processing
queue.appendleft("first")
queue.appendleft("second")
queue.appendleft("third")
# pop values when ready
process(queue.pop()) # would process "first"
# add values while processing
queue.appendleft("fourth")
# what does the queue look like now?
queue # deque(['fourth', 'third', 'second'])
作为一个双端队列,deque还提供了一些其他的好用方法,比如 rotate 等,下面我们一起来看一下:
填充
deque可以从任意一端填充,在python实现称为“左端”和“右端”。
import collections
d1 = collections.deque()
d1.extend('abcdefg')
print 'extend:', d1
d1.append('h')
print 'append:', d1
d2 = collections.deque()
d2.extendleft(xrange(6))
print 'extendleft', d2
d2.appendleft(6)
print 'appendleft', d2
extendleft()迭代处理其输入,对每个元素完成与appendleft()相同的处理。
extend: deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
append: deque(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
extendleft deque([5, 4, 3, 2, 1, 0])
appendleft deque([6, 5, 4, 3, 2, 1, 0])
利用
可以从两端利用deque元素,取决于应用的算法。
import collections
print "From the right:"
d = collections.deque('abcdefg')
while True:
try:
print d.pop(),
except IndexError:
break
print "\nFrom the left:"
d = collections.deque(xrange(6))
while True:
try:
print d.popleft(),
except IndexError:
break
使用pop()可以从deque右端删除一个元素,使用popleft()可以从deque左端删除一个元素。
From the right:
g f e d c b a
From the left:
0 1 2 3 4 5
由于双端队列是线程安全的,可以在不同的线程中同时从两端利用队列的内容。
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)
输出结果:
# 一个无尽循环的跑马灯
------------->-------
0
投稿
猜你喜欢
- 本文主要用python实现了对网站的模拟登录。通过自己构造post数据来用Python实现登录过程。当你要模拟登录一个网站时,首先要搞清楚网
- jQuery.sheet 是一个用于创建 Web 电子表格的 jQuery插件,其功能及界面风格和微软的 Excel 非常相似,使得用户不至
- 一、问题Python模块和C/C++的动态库间相互调用在实际的应用中会有所涉及,在此作一总结。二、Python调用C/C++1、Python
- IDE(集成开发环境)或换句话说PHP编辑器是开发人员在构建移动或Web应用必不可少的工具。在这篇文章中,我们将讨论有关PHP编辑器并分享5
- ajax.html <html><head> <met
- 问题描述:30 个人在一条船上,超载,需要 15 人下船。于是人们排成一队,排队的位置即为他们的编号。报数,从 1 开始,数到 9 的人下船
- 本文实例讲述了Python集中化管理平台Ansible介绍与YAML。分享给大家供大家参考,具体如下:一 中文社区http://ansibl
- 意思就是画四条直线,四条直线都不能相交即可。#!/usr/bin/python#coding: UTF-8import turtleimpo
- 要想更好的理解 css, 尤其是 IE 下对 css 的渲染,haslayout 是一个非常有必要彻底弄清除的概念。大多IE下的显示错误,就
- 前言不要在用手敲生成Excel数据报表了,用Python自动生成Excel数据报表!废话不多说让我们愉快地开始吧~开发工具Python版本:
- 1. 安装Opencv包pip install opvencv-python2.实现代码:视频转为图片:import cv2cap=cv2.
- CSV(Comma-Separated Values)即逗号分隔值,一种以逗号分隔按行存储的文本文件,所有的值都表现为字符串类型(注意:数字
- 技术背景GPU的加速技术在深度学习、量子计算领域都已经被广泛的应用。其适用的计算模型是小内存的密集型计算场景,如果计算的模型内存较大,则需要
- 部署网站前查看一下系统是否已经安装CGI1、启动iis服务器,打开IIS服务器打开IIS服务器,点击网站,右击“添加网站”2、创建网站点击“
- 这篇文章用来整理一下入门深度学习过程中接触到的四种激活函数,下面会从公式、代码以及图像三个方面介绍这几种激活函数,首先来明确一下是哪四种:S
- 一,直接保存pb1, 首先我们当然可以直接在tensorflow训练中直接保存为pb为格式,保存pb的好处就是使用场景是实现创建模型与使用模
- 一、弹窗事件是什么?弹窗事件就是在我们执行某操作的时候,弹出信息框给出提示。或收集数据的时候,弹出窗口收集信息,不想收集可以取消隐藏。二、简
- 一、设计理念1.先写一个登录的py文件,用python的tkinter库2.再写一个py文件用于爬取有道翻译输出栏的内容3.再利用pytho
- 本文实例为大家分享了python3 pillow模块验证码的具体代码,供大家参考,具体内容如下直接放代码吧,该写的注释基本都写了# -*-
- 下面就是今天下午的研究成果。发布系统需要响应用户的中断请求,需要在GET方法中杀掉由subprocess派生的子进程,刚开始直接用os.ki