[循环过程中记录最后/开头 N 次循环结果]在一篇文档中搜索包含特定关键词的行,保存文档最开头包含特定关键词的几行,或文档结尾包含特定关键词的几行 #python #array
✓ Published0🌍 Public
SShawn91
Last edited Jan 20, 2019
Created on Jan 20, 2019
This example demonstrates how to preserve only the last N occurrences of lines matching a keyword while searching through a document, yielding each matching line along with the saved history. The code uses Python’s `collections.deque` with a `maxlen` parameter to automatically drop the oldest entries once the buffer exceeds the specified size. A generator function `search` iterates over the input lines, checks for the keyword pattern, and yields both the current match and the deque containing previous matches. The example input `['abc', 'bcd', 'hahaha', 'acd', 'cef']` is processed with a history limit of 3, producing a final deque showing only the last three matched lines.
AI-generated description