Python Forum
keeping the last 4 records in a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
keeping the last 4 records in a list
#1
i'm reading in lines from a file by looping over the open file object so i have 1 line at a time. i need to do tests that check the last 4 lines. i need to keep a sliding window of the last 4 lines. what i have been doing is:
...
buffer = bytearray()
sw4 = [b'baz\n',b'bar\n',b'foo\n']
with open(fn,'rb') as f:
    for line in f:
        buffer += line
        sw4[:0] = line
        sw4[4:] = []
        ...
is this a good way to do that with sw4 having the last 4 lines in reverse order? are there any nice builtin tools to do this better or more clearly?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
It is not in the standard library, but more_itertools.windowed() looks like the appropriate ideocyte.
Skaperen likes this post
Reply
#3
it looks like more_itertools.windowed() creates an iterator that gives the various windows in the form of an iterator of windows, from a full iterator such as the file object. so i could apply it to the file object and get a window each time that has the new line and the previous N-1 lines. sweet. this is a script for my own use so i can just install it for myself. thanks!
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  savin ideas, keeping notes Skaperen 15 7,133 Mar-31-2018, 10:26 PM
Last Post: Almenon

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020