Question: Want to make a limited history of the last few records during iterations or other forms of processing
Solution: Select Collections.deque.
The following code makes a simple text-matching operation on a series of lines of text, outputting the current matching row and the last checked n-line text when a match is found:
fromCollectionsImportdequedefSearch (lines, pattern, history=5): Previous_lines= Deque (maxlen=History ) forLineinchlines:ifPatterninchLine :yieldLine , Previous_lines previous_lines.append (line)#Example use on a fileif __name__=='__main__': With open ('Somefile.txt') as F: forLine, PrevlinesinchSearch (F,'python', 5): forPlineinchPrevlines:Print(Pline, end="') Print(Line, end="') Print('-'*20)
As in the code above, when you write code that searches for a record, you typically use a generator function that contains the yield keyword to decouple the code that processes the search from the code that uses the search results. Specific generators are described in the "Iterators and Generators" section 3.
Deque (maxlen=n) creates a fixed-length queue that automatically removes the oldest record when a new element is added and the queue is full:
from Import deque>>> q=deque (maxlen=3)>>> q.append (1)>>> q.append (2 )>>> q.append (3)>>> qdeque ([1, 2, 3], maxlen=3)>>> Q.append (4)>>> qdeque ([2, 3, 4], maxlen=3)>>> q.append (5) >>> qdeque ([3, 4, 5], maxlen=3)>>>
Although this can be done manually on the list (append, Del), this solution for the queue is much more elegant and runs much faster.
If you do not specify a queue length, you get a queue with no bounds, and you can perform add and eject operations at both ends:
>>> q=deque ()>>> qdeque ([])>>> q.append (1)>>> Q.append (2)>>> q.append (3)>>> qdeque ([1, 2, 3])>>> Q.appendleft (4)>>> qdeque ([4, 1, 2, 3])>>> q.pop ()3>> > qdeque ([4, 1, 2])>>> q.popleft ()4>>> qdeque ([1, 2 ])>>>
"Python Cookbook" "Data Structure and algorithm" 3. Save the last n elements