[英]How do I reset a list iterator in Python?
For example, in C++ I could do the following :- 例如,在C ++中,我可以执行以下操作: -
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 - 对于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. 基本上在循环过程中,'a'的长度可能会改变。 So every time the length of 'a' changes, I want to start the loop over. 所以每次'a'的长度发生变化时,我都想开始循环。 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: 不使用for
,而是使用while
循环手动执行:
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 您可以通过直接比较i
和len(a)
,或者在循环中调用n=len(a)
来进一步移动终点线
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.