Sunnnner

duque函数有一个maxlen参数,当append的时候,如果超过,那么最前面的就会被挤出队列

from collections import duque
def search(lines, pattern, lens=5):
previous_lines = deque(maxlen=lens)
for li in lines:
if pattern in li:
yield li, previous_lines
previous_lines.append(li)

if name == ‘main‘:
with open(r’./xx.txt’) as f:
for line, prevlines in search(f, ‘python’, 5):
for pline in prevlines:
print(pline, end=’’)
print(line, end=’’)
print(‘**’ * 20)
```


这是文章页脚,可以设置打赏图片:
![](https://img.vim-cn.com/4a/5f8244a7c6e1e069a781b84ed11008e7955e16.png)

 Comments