Python迭代器有has_next方法吗?


当前回答

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

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

其他回答

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

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

使用next(迭代器,default_value)可以替代StopIteration。

For exapmle:

>>> a = iter('hi')
>>> print next(a, None)
h
>>> print next(a, None)
i
>>> print next(a, None)
None

因此,如果你不想用异常方式,你可以为None或其他预先指定的值检测迭代器的end。

我相信python只有next(),根据文档,如果没有更多的元素,它就会抛出异常。

http://docs.python.org/library/stdtypes.html#iterator-types

除了所有提到的StopIteration, Python的“for”循环只是做你想要的:

>>> it = iter("hello")
>>> for i in it:
...     print i
...
h
e
l
l
o