标签:col class line 怎么办 some 处理 print sea nbsp
1、deque(maxlen=N)创建一个固定长度的队列,当有新的记录加入而队列已经满时,会自动移除老的记录.
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)
应用功能:
from collections import deque def search(lines, pattern, history=5): previous_lines = deque(maxlen=history) #collection.deque : deque (maxlen=N)创建了一个固定长度的队列,当有新的队列已满时会自动移除最老的那条记录 # deque([], maxlen=5) 创建一个队列 for line in lines: print(‘当前要匹配行:‘, line) if pattern in line: yield line, previous_lines # previous: deque([‘python1\n‘, ‘python2\n‘, ‘怎么办呢,\n‘], maxlen=5) if __name__ == ‘__main__‘: with open(‘somefile.txt‘) as f: for line, previous in search(f, ‘python‘, 5): # 调用search函数,每次yield当前匹配的文本和最后匹配检查过的N行文本 print(‘line:‘,line,‘previous:‘,previous) for pline in previous: print(‘最后匹配检查过的N行文本:‘,pline, end=‘‘) print(‘-‘ * 20) """ somefile.txt文本内容: python1 python2 怎么办呢, 失效一处python3。 输出: 当前要匹配行: python1 line: python1 previous: deque([], maxlen=5) -------------------- 当前要匹配行: python2 line: python2 previous: deque([‘python1\n‘], maxlen=5) 最后匹配检查过的N行文本: python1 -------------------- 当前要匹配行: 怎么办呢, 当前要匹配行: 失效一处python3。 line: 失效一处python3。 previous: deque([‘python1\n‘, ‘python2\n‘, ‘怎么办呢,\n‘], maxlen=5) 最后匹配检查过的N行文本: python1 最后匹配检查过的N行文本: python2 最后匹配检查过的N行文本: 怎么办呢, -------------------- """
python之保留有限的历史记录(collections.deque)
标签:col class line 怎么办 some 处理 print sea nbsp
原文地址:https://www.cnblogs.com/zzy-9318/p/9839314.html