Has Next in Python Iterators
Paul Rudin
paul.nospam at rudin.co.uk
Mon Oct 25 13:14:01 EDT 2010
Kelson Zawack <zawackkfb at gis.a-star.edu.sg> writes:
> The example I have in mind is list like [2,2,2,2,2,2,1,3,3,3,3] where
> you want to loop until you see not a 2 and then you want to loop until
> you see not a 3.
"loop until you see not a 2" - you mean yield 2s as long as there are 2s
to be consumed?
"loop until you see not a 3" - you mean yield 3s as long as there are 3s
to be consumed?
So in this case you'd see just the initial 2s? (Since the 1 immediately
follows the 2s and is "not a 3")
def twos_then_threes(iterable):
i = iter(iterable)
n = i.next()
while n==2:
yield n
n=i.next()
while n==3:
yield n
n=i.next()
so... no need for any has_next()
or do I misunderstand what you want to do? Probably this can be done
with some itertools.groupby() cunningness...
More information about the Python-list
mailing list