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个元素的更多相关文章

  1. appium 学习各种小功能总结--功能有《滑动图片、保存截图、验证元素是否存在、》---新手总结(大牛勿喷,新手互相交流)

    1.首页滑动图片点击 /** * This Method for swipe Left * 大距离滑动 width/6 除数越大向左滑动距离也越大. * width:720 *height:1280 ...

  2. Python:读取txt中按列分布的数据,并将结果保存在Excel文件中 && 保存每一行的元素为list

    import xlwt import os def write_excel(words,filename): #写入Excel的函数,words是数据,filename是文件名 wb=xlwt.Wor ...

  3. 【python cookbook】【数据结构与算法】3.保存最后N个元素

    问题:希望在迭代或是其他形式的处理过程中对最后几项记录做一个有限的历史记录统计 解决方案:选择collections.deque. 如下的代码对一系列文本行做简单的文本匹配操作,当发现有匹配时就输出当 ...

  4. 给定字符串数组,用map的key保存数组中字符串元素,value保存字符串元素出现次数,最后统计个字符串元素出现次数

    import java.util.HashMap; public class map1 { public static void main(String[] args) { String[] arra ...

  5. jQuery--Dom元素隐藏和显示原理(源码2.0.3)

    对于Dom元素显示和隐藏的操作,jQuery提供了比较方便的函数,我们也经常使用: 1. show() : 显示Dom元素2. hide() : 隐藏Dom元素3. toggle() : 改变Dom元 ...

  6. js原生封装getClassName()方法-ie不支持getElementsByClassName,所以要自己实现获取类名为className的所有元素

    <html> <head> <script type="text/javascript"> window.onload = function() ...

  7. 求链表的倒数第m个元素

    法一: 首先遍历一遍单链表,求出整个单链表的长度n,然后将倒数第m个,转换为正数第n-m+1个,接下去遍历一次就可以得到结果. 不过这种方法需要对链表进行两次遍历,第一次遍历用于求解单链表的长度,第二 ...

  8. [Perl] 删除数组中重复元素

    写一个小程序时候,需要去除一个数组中的重复元素,搜索了一下,找到的代码主要是两种,一种是使用grep函数,一种是转换为hash表,代码分别如下: 使用grep函数代码片段:代码: my @array ...

  9. POI读取Excel数据保存到数据库,并反馈给用户处理信息(导入带模板的数据)

    今天遇到这么一个需求,将课程信息以Excel的形式导入数据库,并且课程编号再数据库中不能重复,也就是我们需要先读取Excel提取信息之后保存到数据库,并将处理的信息反馈给用户.于是想到了POI读取文件 ...

随机推荐

  1. 「Linux」centos7安装mysql

    1.yum仓库下载MySQL:sudo yum localinstall https://repo.mysql.com//mysql80-community-release-el7-1.noarch. ...

  2. u3d图片转视频

    c#代码://将截图生成视频public static void createVideo(){ ProcessStartInfo psi = new ProcessStartInfo(); psi.F ...

  3. Java集合框架(list,Queue)

    List和Queue都继承自Collection接口 list常规用法 List判断两个对象相等的标准:equals方法返回true class A2 { public boolean equals( ...

  4. MySql 插入数据库报错 Incorrect string value: '\xF0\xA0\x86\xA2'

    今天从nginx日志分析搜索关键字,然后把关键字插入到Mysql数据库里,出现如下错误 SQL state [HY000]; error code [1366]; Incorrect string v ...

  5. 一般处理程序、ASP.NET核心知识(5)

    初窥 1.新建一个一般处理程序 新建一个一般处理程序 2.看看里头的代码 public class MyHandler : IHttpHandler { public void ProcessRequ ...

  6. ue4 TimeRemaining(ratio)找不到的问题

    最近看ue4的Blueprint 3rd Person Game的教学视频,其中第十集https://docs.unrealengine.com/latest/INT/Videos/PLZlv_N0_ ...

  7. Angular 2.0 基础:服务

    什么是服务(Service) 在Angular 2 中我们提到的服务 service 一般指的是 哪些能够被其他组件或者指令调用的 单一的,可共享的 代码块.当然,通过服务可以将数据和组件分开,这样就 ...

  8. python并发编程之threading线程(一)

    进程是系统进行资源分配最小单元,线程是进程的一个实体,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位.进程在执行过程中拥有独立的内存单元,而多个线程共享内存等资源. 系列文章 py ...

  9. Linux下查看进程占用内存的最好方式

    今天看到stackoverflow上关于linux下如何查看某个进程占用的内存是多少的回答,觉得非常棒,不过是全英文的,很多人可能看不懂,所以我翻译一下 翻译自http://stackoverflow ...

  10. Elasticsearch5.0 安装问题集锦【转】

    转自 Elasticsearch5.0 安装问题集锦 - 代码&优雅着&生活 - 博客园http://www.cnblogs.com/sloveling/p/elasticsearch ...