grokking generators and iterators

David Eppstein eppstein at ics.uci.edu
Sat May 11 00:52:30 EDT 2002


In article <3CDCAEDC.2030103 at horvath.com>,
 Bob Horvath <usenet at horvath.com> wrote:

> I don't think it matters what the format is. It is a repeating pattern 
> of 5 lines.
> 
> How would you suggest writing a generator that spits out 5 line chunks 
> of a file at a time?

def fiveatatime(L):
    L = iter(L)
    while 1:
        yield (L.next(),L.next(),L.next(),L.next(),L.next())

then call fiveatatime(file)

This will group each five line chunk into a tuple of five strings.
It will throw away lines at the end that are not a multiple of five -- 
you need to specify more carefully what to do if that is a problem.

-- 
David Eppstein       UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/



More information about the Python-list mailing list