如何在Python中重置列表迭代器? [英] How do I reset a list iterator in Python?

查看:452
本文介绍了如何在Python中重置列表迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在C ++中,我可以执行以下操作:-

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, i.e. start the loop over without introducing a second loop

对于Python-

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

基本上,在循环过程中,"a"的长度可能会改变.因此,每次"a"的长度更改时,我都想重新开始循环.我该怎么做呢?

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

像这样使用它:

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

这篇关于如何在Python中重置列表迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆