简体   繁体   中英

How do I reset a list iterator in Python?

For example, in C++ I could do the following :-

for (i = 0; i < n; i++){
    if(...){              //some condition
        i = 0;
    }
}

This will effectively reset the loop, ie start the loop over without introducing a second loop

For Python -

for x in a: # 'a' is a list
    if someCondition == True:
        # do something

Basically during the course of the loop the length of 'a' might change. So every time the length of 'a' changes, I want to start the loop over. How do I go about doing this?

You could define your own iterator that can be rewound:

class ListIterator:
    def __init__(self, ls):
        self.ls = ls
        self.idx = 0
    def __iter__(self):
        return self
    def rewind(self):
        self.idx = 0
    def __next__(self):
        try:
            return self.ls[self.idx]
        except IndexError:
            raise StopIteration
        finally:
            self.idx += 1

Use it like this:

li = ListIterator([1,2,3,4,5,6])
for element in li:
    ... # do something
    if some_condition:
        li.rewind()

Not using for , but doing by hand with a while loop:

n = len(a)
i = 0
while i < n:
  ...
  if someCondition:
    n = len(a)
    i = 0
    continue
  i+=1

edit - if you're just appending to the end, do you really need to start over? You can just move the finish line further, by comparing i to len(a) directly, or calling n=len(a) in your loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM