保存最后N个元素
cookbook系列
问题:对要搜索的值的最后几项做个有限的历史记录。
方案:
#coding=utf-
from collections import deque def search(lines, pattern, history=):
previous_lines = deque(maxlen=history) #deque双端队列
for line in lines:
if pattern in line:
yield line, previous_lines #生成器,双端队列保存5个,意味着在找到pattern之前会记录5行数据,pattern就在line里面
previous_lines.append(line) # Example use on a file
if __name__ == '__main__':
with open('somefile.txt') as f:
for line, prevlines in search(f, 'python', ):
for pline in prevlines:
print pline, #先输出队列里的5个
print line, #在输出pattern的line
print('-'*)
案例文件:somefile.txt
=== Keeping the Last N Items ==== Problem You want to keep a limited history of the last few items seen
during iteration or during some other kind of processing. ==== Solution Keeping a limited history is a perfect use for a `collections.deque`.
For example, the following code performs a simple text match on a
sequence of lines and prints the matching line along with the previous
N lines of context when found: [source,python]
----
from collections import deque def search(lines, pattern, history=):
previous_lines = deque(maxlen=history)
for line in lines:
if pattern in line:
for pline in previous_lines:
print(lline, end='')
print(line, end='')
print()
previous_lines.append(line) # Example use on a file
if __name__ == '__main__':
with open('somefile.txt') as f:
search(f, 'python', )
---- ==== Discussion Using `deque(maxlen=N)` creates a fixed size queue. When new items
are added and the queue is full, the oldest item is automatically
removed. For example: [source,pycon]
----
>>> q = deque(maxlen=)
>>> q.append()
>>> q.append()
>>> q.append()
>>> q
deque([, , ], maxlen=)
>>> q.append()
>>> q
deque([, , ], maxlen=)
>>> q.append()
>>> q
deque([, , ], maxlen=)
---- Although you could manually perform such operations on a list (e.g.,
appending, deleting, etc.), the queue solution is far more elegant and
runs a lot faster. More generally, a `deque` can be used whenever you need a simple queue
structure. If you don't give it a maximum size, you get an unbounded
queue that lets you append and pop items on either end. For example: [source,pycon]
----
>>> q = deque()
>>> q.append()
>>> q.append()
>>> q.append()
>>> q
deque([, , ])
>>> q.appendleft()
>>> q
deque([, , , ])
>>> q.pop() >>> q
deque([, , ])
>>> q.popleft() ---- Adding or popping items from either end of a queue has O()
complexity. This is unlike a list where inserting or removing
items from the front of the list is O(N).
运行结果:
H:\Python27_64\python.exe H:/myfile/python-cookbook-master/src//keeping_the_last_n_items/example.py
Keeping a limited history is a perfect use for a `collections.deque`.
For example, the following code performs a simple text match on a
sequence of lines and prints the matching line along with the previous
N lines of context when found: [source,python]
--------------------
previous_lines.append(line) # Example use on a file
if __name__ == '__main__':
with open('somefile.txt') as f:
search(f, 'python', )
-------------------- 进程已结束,退出代码0
讨论:
第5行双端队列deque的用法
固定长度队列:
>>> q = deque(maxlen=)
>>> q.append()
>>> q.append()
>>> q.append()
>>> q
deque([, , ], maxlen=)
>>> q.append()
>>> q
deque([, , ], maxlen=)
>>> q.append()
>>> q
deque([, , ], maxlen=)
双端队列:
>>> q = deque()
>>> q.append()
>>> q.append()
>>> q.append()
>>> q
deque([, , ])
>>> q.appendleft()
>>> q
deque([, , , ])
>>> q.pop() >>> q
deque([, , ])
>>> q.popleft()
4
两者皆有:设置好固定长度时,左右两端均可添加和删除

使用双端队列要比列表 方便、简洁!
保存最后N个元素的更多相关文章
- appium 学习各种小功能总结--功能有《滑动图片、保存截图、验证元素是否存在、》---新手总结(大牛勿喷,新手互相交流)
1.首页滑动图片点击 /** * This Method for swipe Left * 大距离滑动 width/6 除数越大向左滑动距离也越大. * width:720 *height:1280 ...
- Python:读取txt中按列分布的数据,并将结果保存在Excel文件中 && 保存每一行的元素为list
import xlwt import os def write_excel(words,filename): #写入Excel的函数,words是数据,filename是文件名 wb=xlwt.Wor ...
- 【python cookbook】【数据结构与算法】3.保存最后N个元素
问题:希望在迭代或是其他形式的处理过程中对最后几项记录做一个有限的历史记录统计 解决方案:选择collections.deque. 如下的代码对一系列文本行做简单的文本匹配操作,当发现有匹配时就输出当 ...
- 给定字符串数组,用map的key保存数组中字符串元素,value保存字符串元素出现次数,最后统计个字符串元素出现次数
import java.util.HashMap; public class map1 { public static void main(String[] args) { String[] arra ...
- jQuery--Dom元素隐藏和显示原理(源码2.0.3)
对于Dom元素显示和隐藏的操作,jQuery提供了比较方便的函数,我们也经常使用: 1. show() : 显示Dom元素2. hide() : 隐藏Dom元素3. toggle() : 改变Dom元 ...
- js原生封装getClassName()方法-ie不支持getElementsByClassName,所以要自己实现获取类名为className的所有元素
<html> <head> <script type="text/javascript"> window.onload = function() ...
- 求链表的倒数第m个元素
法一: 首先遍历一遍单链表,求出整个单链表的长度n,然后将倒数第m个,转换为正数第n-m+1个,接下去遍历一次就可以得到结果. 不过这种方法需要对链表进行两次遍历,第一次遍历用于求解单链表的长度,第二 ...
- [Perl] 删除数组中重复元素
写一个小程序时候,需要去除一个数组中的重复元素,搜索了一下,找到的代码主要是两种,一种是使用grep函数,一种是转换为hash表,代码分别如下: 使用grep函数代码片段:代码: my @array ...
- POI读取Excel数据保存到数据库,并反馈给用户处理信息(导入带模板的数据)
今天遇到这么一个需求,将课程信息以Excel的形式导入数据库,并且课程编号再数据库中不能重复,也就是我们需要先读取Excel提取信息之后保存到数据库,并将处理的信息反馈给用户.于是想到了POI读取文件 ...
随机推荐
- SSM与SSH的对比
struts与springMVC的对比: 1.核心控制器(前端控制器.预处理控制器):负责接收页面请求和返回数据给页面. 对于使用过mvc框架的人来说这个词应该不会陌生,核心控制器的主要用途是处理所有 ...
- [DeeplearningAI笔记]卷积神经网络1.2-1.3边缘检测
4.1卷积神经网络 觉得有用的话,欢迎一起讨论相互学习~Follow Me 1.2边缘检测示例 边缘检测可以视为横向边缘检测和纵向边缘检测如下图所示: 边缘检测的原理是通过一个特定构造的卷积核对原始图 ...
- Java设计模式の代理模式
目录 代理模式 1.1.静态代理 1.2.动态代理 1.3.Cglib代理 代理模式 代理(Proxy)是一种设计模式,提供了对目标对象另外的访问方式;即通过代理对象访问目标对象.这样做的好处是 ...
- background(css复合写法)
1. 背景-background========================================================== 单个属性的写法 .sample1 { /*背景颜色 ...
- 修改tomcat的Response Hearder 头中的Server信息
如图: Server: Apache-Coyote/1.1 这个信息给入侵者提供了一定的指示作用.为了安全起见,要求更改这个信息.那么我们就来修改一下试试,非常简单,只要在Connector中添加se ...
- R3—日期处理
一. 问题引入 下面是一个房地产价格数据,现在想要提取2008年6月份的数据进行分析,在R中该如何操作呢? city price bedrooms squarefeet lotsize latitud ...
- 【BZOJ】2301: [HAOI2011]Problem b
[题意]于给出的n个询问,每次求有多少个数对(x,y),满足a≤x≤b,c≤y≤d,且gcd(x,y) = k,gcd(x,y)函数为x和y的最大公约数.n,a,b,c,d,k<=50000. ...
- 【BZOJ】1537: [POI2005]Aut- The Bus
[算法]DP+线段树求区间max(二维偏序) [题解] 状态转移方程:f[i]=max(f[j]+v[i]),x[j]<x[i]&&y[j]<y[i]. 观察j的条件限制显 ...
- 详细说说如何生成验证码—ASP.NET细枝末节(4)
前言 今天小编详细的说一下,ASP.NET网站开发过程中生成验证码的全部问题. 本文的目标,是让读者了解,生成验证码涉及的全部基础知识问题. 当然这里说的是比较简单的验证码. 真正符合要求的验证码,涉 ...
- XML & JSON---iOS-Apple苹果官方文档翻译
技术博客http://www.cnblogs.com/ChenYilong/ 新浪微博http://weibo.com/luohanchenyilong //转载请注明出处--本文永久链接 ...