grokking generators and iterators

Chris Liechti cliechti at gmx.net
Sat May 11 11:16:07 EDT 2002


David Eppstein <eppstein at ics.uci.edu> wrote in
news:eppstein-049A38.22415410052002 at news.service.uci.edu: 
> In article <3CDCB6AF.8030903 at horvath.com>,
>  Bob Horvath <usenet at horvath.com> wrote:
> 
>> > 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. 
>> > 
>> 
>> 
>> That will indeed work, I think, but I am not sure I understand the
>> end condition.  What happens when you "next()" off of the end? I was 
>> expectin an exception, but it seems to get swallowed.
> 
> You would typically use this in a for-loop:
> 
> for chunk in fiveatatime(file):
>     do something
> 
> The exception terminates the loop.

but if the file doesn't contain a multiple of five you will get an 
exception instead of return the e.g. four lines that only where there.

if that's no problem fine, but otherwise fiveatatime should be modified 
that it catches StopIteration on all the next() but the first one (maybe 
returning an empty string for the missing lines).

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list