Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate N items at a time on a generator with single yield

Tags:

python-3.x

How do I do that? islice() return n items at a time but I can't figure out how to iterate it. Right now I do something like this:

# -*- coding: utf-8 -*-
'''
   print 3 lines at a time.
'''

def myread(filename):
  with open(filename,'r',encoding='utf-8-sig') as f:
    for line in f:
        yield line.strip()

filename = 'test.txt'
temp = []
for res_a in myread(filename):
  temp.append(res_a)
  if len(temp)==3:
    print(temp)
    temp = []
print(temp)

Note that I don't know how big is my text file.

like image 936
maugch Avatar asked Oct 22 '25 03:10

maugch


1 Answers

You can use itertools.islice and the two argument form of iter, eg:

from itertools import islice

with open('file') as fin:
    # gen-comp yielding stripped lines
    lines = (line.strip() for line in fin)
    # create list of at most 3 lines from the file's current position 
    # and use an empty list as a sentinel value of when to stop... (no more lines)
    for three in iter(lambda: list(islice(lines, 3)), []):
        print(three)

As a function:

def myread(filename): 
    with open(filename) as fin:
        lines = (line.strip() for line in fin)
        yield from iter(lambda: list(islice(lines, 3)), [])
like image 115
Jon Clements Avatar answered Oct 26 '25 18:10

Jon Clements



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!