this article illustrates how Python saves the last N elements. Share to you for your reference, as follows:

: in the hope of iteration or a limited history of statistics

on the last recording process in other forms of solutions: collections.deque.

follows the code to do a simple text on a series of text matching operation, when a N line of text matching output matching line current and finally checked:

 from collections import deque def search (lines, pattern, history=5): previous_lines = deque (maxlen=history) for line in lines: if pattern in line: yield line previous_lines 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', 5): for pline in prevlines: print (pline, end='') print (line, end='') print ('-'*20) 

, like the above code, is usually used to generate generator functions containing yield keyword when writing code to search for a record, decoupling the code that processes the search process from the code that uses search results. The specific generator can refer to the content of the station iterator and generator.

deque (maxlen=N) to create a fixed length of the queue, and the queue is full when adding a new element that will automatically remove the old record:

 > > > from collections; import deque > > > q=deque (maxlen=3) > > > q.append (1) > > > q.append (2) > > > q.append (3) > > > Q deque ([1, 2, 3], maxlen=3) > > > q.append (4) > > > Q deque ([2, 3, 4], maxlen=3) & gt; > > q.append (5) > > > Q deque ([3, 4, 5], maxlen=3) > > > 

, though you can do this operation on the list manually (append, Del), but the queue of this solution is much more elegant, running much more quickly.

如果不指定队列长度,则得到一个无界限的队列,可在两端执行添加和弹出操作:

 >>> q=deque() >>> q deque([]) >>> q.append(1) >>> q.append(2) >>> q.append(3) >>> q deque([1, 2, 3]) >>> q.appendleft(4) >>> q deque([4, 1, 2, 3]) >>> q.pop() 3 >>> q deque([4, 1, 2]) >>> q.popleft() 4 >>> q deque([1, 2]) >>>  

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结 "And" Python ", summarizes the skills in the use of function" Python "string manipulation skills summary and" Python entry and advanced tutorial classic "

to the Python program designed to help all of you.

you might be interested in this article:

realization method


This concludes the body part

This paper fixed link:http://www.script-home.com/python-cookbook-data-structure-and-algorithm-methods-to-save-the-last-n-elements.html | Script Home | +Copy Link

Article reprint please specify:Python Cookbook (data structure and algorithm) methods to save the last N elements | Script Home

You may also be interested in these articles!