保存最后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读取文件 ...
随机推荐
- winform设计一个登录界面和修改密码的界面-自动切换窗体(问题[已解] 望一起讨论)(技术改变世界-cnblog)
http://www.cnblogs.com/IAmBetter/archive/2012/01/14/2322156.html winform设计一个登录界面和修改密码的界面-自动切换窗体(问题[已 ...
- php7实现基于openssl的加密解密方法
还需要注意的是加密字符串长度问题,如果加密字符串长度太长需要进行分段加解密,如下代码: 加密:(公匙加密,私密一般用来解密) function encrypt($originalData){ $pub ...
- Java修饰符 public、protected、default、private
2.访问修饰符public,private,protected,以及不写(默认)时的区别?答: 修饰符 当前类 同 包 子 类 其他包 public √ √ √ √ protected √ √ √ × ...
- Bootstrap3和Bootsrap4的区别
Bootstrap3和Bootstap4的区别 1.Bootsrap4 css文件减少了40%以上 2.Bootsrap4已经不支持IE8以及IOS 6的支持 3.多了些类好组件
- 算法专题-STL篇
这篇文章着重记录c++中STL的用法.主要粗略的介绍其用法,以知识点的形式呈现其功能,不会深入源码分析其工作原理. 排序和检索. sort(a,a+n),对a[0]往后的n个元素(包括a[0])进行排 ...
- 数学&搜索:博弈论之极大极小搜索与alpha-beta减枝
目的是寻找最优的方案使得自己能够利益最大化. 基本思想就是假设自己(A)足够聪明,总是能选择最有利于自己的方案,而对手(B)同样足够聪明,总会选择最不利A的方案 对抗搜索就是对于先手来说,取后手中状态 ...
- .NET Framework 4安装失败
#刚装系统遇到之前所遇到的问题.之前因为这个事情还被困扰了好一阵子.特此写出来分享给大家. 环境:WIN10 企业版 在使用一些需要较高.net版本的时候无法更新.你可以试一下.在服务里面开启再更新. ...
- lspci 虚拟机网卡对应关系
我这个办法有点笨: 到 /sys/devices/ 下去搜索网卡 eth*,找到网卡对应的PCI 总线位置,例如:05:00.0. 然后通过 "lspci -s 05:00.0" ...
- CentOS中搭建Redis伪分布式集群【转】
解压redis 先到官网https://redis.io/下载redis安装包,然后在CentOS操作系统中解压该安装包: tar -zxvf redis-3.2.9.tar.gz 编译redis c ...
- UVALive 3668 A Funny Stone Game
题目链接:UVALive - 3668 题目大意为给定n堆石子,每次的操作是选择三个数i<j<=k,从i中拿一枚石子,在j和k中分别放入一枚石子.不能操作者输.求先手是否能赢,若可以,则输 ...