Rah*_*kar 4 python iteration loops list
例如,在C ++中,我可以执行以下操作:
for (i = 0; i < n; i++){
if(...){ //some condition
i = 0;
}
}
Run Code Online (Sandbox Code Playgroud)
这将有效地重置循环,即在不引入第二个循环的情况下重新开始循环
对于Python-
for x in a: # 'a' is a list
if someCondition == True:
# do something
Run Code Online (Sandbox Code Playgroud)
基本上在循环过程中,“ a”的长度可能会改变。因此,每次“ a”的长度更改时,我都想重新开始循环。我该怎么做呢?
您可以定义自己的可以重绕的迭代器:
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
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
li = ListIterator([1,2,3,4,5,6])
for element in li:
... # do something
if some_condition:
li.rewind()
Run Code Online (Sandbox Code Playgroud)