Python迭代器没有hasNext
方法吗?
发布于 2009-12-28 02:08:52
不,没有这样的方法。迭代结束时会出现一个异常。请参阅documentation。
发布于 2013-03-25 11:05:17
通过使用next(iterator, default_value)
,有一种替代StopIteration
的方法。
对于exapmle:
>>> a = iter('hi')
>>> print next(a, None)
h
>>> print next(a, None)
i
>>> print next(a, None)
None
因此,如果您不想使用异常方法,可以检测for None
或其他预先指定的迭代器末尾的值。
发布于 2009-12-28 10:52:55
除了提到StopIteration之外,Python "for“循环只做您想要做的事情:
>>> it = iter("hello")
>>> for i in it:
... print i
...
h
e
l
l
o
https://stackoverflow.com/questions/1966591
复制相似问题