split an iteration
Peter Otten
__peter__ at web.de
Fri Apr 1 03:59:39 EST 2005
Robin Becker wrote:
> eg for
> >>> e = enumerate([0,1,2,3,4,5])
> >>> for i,a in e:
> ... if a==3: break
> ...
> >>> for i,a in e:
> ... print i,a
> ...
> 4 4
> 5 5
> >>>
>
> I think the second loop needs to start at 3 ie the split needs to be
> start, limit semantics
>
> It would be nice to be able to fix it with a move back method.
I have to reread your previous post, it seems. Meanwhile:
>>> e = enumerate(range(6))
>>> for i, a in e:
... if a == 3:
... for i, a in itertools.chain([(i, a)], e):
... print i, a
... break
...
3 3
4 4
5 5
Nesting the loops is necessary to handle empty lists and lists with no
matching item correctly. Alternatively, you could set a 'found' flag.
Another option:
>>> def predicate((i, a)): return a != 3
...
>>> for i, a in itertools.dropwhile(predicate, enumerate(range(6))):
... print i, a
...
3 3
4 4
5 5
The extra function call might have a negative impact on performance, though.
Peter
More information about the Python-list
mailing list