[Tutor] __iter__ loops, partitioning list among children
Lie Ryan
lie.1296 at gmail.com
Tue Aug 26 22:05:45 CEST 2008
>
> > Just for the sake of argument, here's the principle I'm working
> from:
> >
> > #####
> >>>> lst = range(10)
> >>>> iterlst = iter(lst)
> >>>> iterlst.next()
> > 0
> >>>> for x in iterlst:
> > ... if x < 5:
> > ... print x
> > ... else:
> > ... break
> > ...
> > 1
> > 2
> > 3
> > 4
> >>>> for x in iterlst:
> > ... print x
> > ...
> > 6
> > 7
> > 8
> > 9
> > #####
If that contrived case is the case, you could change the code a bit to
make 5 appears:
for x in iterlst:
print x
if x >= 5: break
for x in iterlst:
print x
> >
> > So that's why I'm creating the iterator outside of the while loop in
> the
> > original code, and then using a repeated for loop with a break to
> step
> > through all the events only once. Of course, the fact that 5 isn't
> in there
> > probably points to the source of my problems! The solution might be
> > assigning iterlist.next() to a variable, and advancing the variable.
>
> The problem is that the first loop consumes the 5 from the iterator
> but doesn't actually process it. That is why you need an iterator with
> push-back - so you can put the 5 "back in" the iterator and get it out
> again in the next loop.
> http://code.activestate.com/recipes/502304/
> Though working with indices directly might be simpler.
More information about the Tutor
mailing list