Python迭代器有has_next方法吗?


当前回答

为了读取所有迭代,基于处理“StopIteration”执行的解决方法非常简单:

    end_cursor = False
    while not end_cursor:
        try:
            print(cursor.next())
        except StopIteration:
            print('end loop')
            end_cursor = True
        except:
            print('other exceptions to manage')
            end_cursor = True

其他回答

你可以使用itertools来tee迭代器。在teed迭代器上检查StopIteration。

不。最类似的概念很可能是StopIteration异常。

我解决问题的方法是保留到目前为止迭代的对象数量的计数。我想通过调用实例方法遍历一个集合。因为我知道集合的长度,以及到目前为止计数的项的数量,所以我有效地使用了hasNext方法。

我的代码的一个简单版本:

class Iterator:
    # s is a string, say
    def __init__(self, s):
        self.s = set(list(s))
        self.done = False
        self.iter = iter(s)
        self.charCount = 0

    def next(self):
        if self.done:
            return None
        self.char = next(self.iter)
        self.charCount += 1
        self.done = (self.charCount < len(self.s))
        return self.char

    def hasMore(self):
        return not self.done

当然,这个例子是一个玩具,但您可以理解。这在无法获取可迭代对象长度的情况下不起作用,比如生成器等。

在任意迭代器对象中尝试__length_hint__()方法:

iter(...).__length_hint__() > 0

使用“for”可以实现他自己版本的“next”避免异常

def my_next(it):
    for x in it:
        return x
    return None