Skip to content

Instantly share code, notes, and snippets.

@loneshark99
Created October 6, 2021 23:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loneshark99/ac79dd26eaef143c89dccf6bbe59b852 to your computer and use it in GitHub Desktop.
Save loneshark99/ac79dd26eaef143c89dccf6bbe59b852 to your computer and use it in GitHub Desktop.
(Python) Keeping the Last N items
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)
if __name__ == '__main__':
with open('/mnt/c/Merge.cs') as f:
for line, prevlines in search(f, 'dense', 5):
for pline in prevlines:
print(pline, end=' ')
print(line, end='')
print('-'*100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment