Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 iterating an interator partially then resuming
#1
i would like to iterate an iterator in a loop that will usually break out part way through. then later, i want another loop to resume that iteration from where the first one left off. how hard is this to do? what if there is a different need between these loops, perhaps in a function, to iterate that iterator from the beginning, maybe stopping at a different position? what seems like it would be useful is something that can make a stateful view of an iterator.
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Quote
#2
Iterators are objects, just like everything else:

>>> x = list(range(10))
>>> it = iter(x)
>>> for a in it:
...     print(a)
...     if a == 4:
...         break
...
0
1
2
3
4
>>> for b in it:
...     print(b)
...
5
6
7
8
9
However, I don't believe you can make iterators go backwards. You could recreate the iterator. You could also make a wrapper class for an iterator that keeps track of what was already iterated over in a stack, and then call it back somehow.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote
#3
looks like exactly what i need. thanks!

the middle iteration can just run from the original or an iterator copy of the original.
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Quote
#4
looks like i have a case where the item i got from the iterator needs to be put back in the iterator so the 2nd loop processes that item again. this case is iterating over some command line arguments and breaking out when it hits a filename. then the 2nd loop finishes the filenames.

i also wonder if i could iterate nested. that is a deeper loop inside the outer loop with both loops iterating over the same iterator ... so the inner one can work on more than one item. but i'd still like to have the last item pushed back into/onto the iterator. i have been doing this in the past by make a list from the iterator then where needed, inserting items into the front of the list. but this all involved more code to handle details like popping items from a list inside a while True: loop.
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  [3.4.4] Last loop element partially done nolme 5 692 May-08-2018, 03:25 PM
Last Post: snippsat

Forum Jump:


Users browsing this thread: 1 Guest(s)