Resuming List Reading And Remembering The Cursor
Solution 1:
Your first loop works fine,you can add print "**********"
after your first for
loop!to see the result.
But for second loop you have a miss understanding, because in second loop you cant iterate over your list from that part you have convert falg
to False
! the second loop will began from start,so you can save the index of the last element in first loop to indx
variable and pass it to your function :
items = range(0, 5)
flag = Truedefvalues(indx):
for v in items[indx:]:
whilenot flag:
yieldNoneyield v
defread(indx=0):
for i in values(indx):
if i isNone:
returnyield i
defrun():
global flag
global indx
# should print just 0 1 2for i,j inenumerate(read(),1):
if j == 2:
flag = False
indx=i
print j
print"**********"# should print just 3 4
flag = Truefor i in read(indx):
print i
print'********'
run()
result :
0
1
2
**********
3
4
********
Solution 2:
You cannot do what you want with the generator; generators are specialised iterators, and iterators can only be iterated over once. Once they are exhausted (StopIterator
has been raised), they cannot yield more items.
Your code on the other hand expects StopIteration
to be raised (the first loop ends), and then a second loop continues to iterate again.
Instead of handling this in the generator, simply stop iterating. Create the generator once, then use it in both loops:
def run():
iterator = read()
for i in iterator:
print i
if i == 2:
break# stop iteratingprint'flip'# resume iteratingfor i in iterator:
print i
Solution 3:
To do this would be fundamentally broken according the Python's iterator protocol:
The intention of the protocol is that once an iterator’s next() method raises StopIteration, it will continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken.
What you should do is make this a class and store the index as an instance variable. This way you do not have to pass in arguments or rely on a global variable.
Solution 4:
You may find the generator below of interest. Using a generator's send()
method we can send data back to the generator. See Yield expressions in the Python docs for further info on this feature. (The Python 3 version of that doc is here).
#!/usr/bin/env pythondeflatched_iter(iterable):
''' Yield items from iterable only when latch is True '''
latch = FalsewhileTrue:
latch = yield iterable.next() if latch elseNonedefmain():
gen = latched_iter(iter('abcdefghijklmnop'))
gen.send(None)
for i in xrange(25):
try:
val = gen.send(i < 5or i >= 10)
except StopIteration:
breakprint i, val
if __name__ == '__main__':
main()
output
0a1b2 c
3 d
4 e
5None6None7None8None9None10 f
11 g
12 h
13i14 j
15 k
16 l
17 m
18 n
19 o
20p
Post a Comment for "Resuming List Reading And Remembering The Cursor"