我有一个生成器,我想知道我是否可以使用它而不必担心 StopIteration ,我想在没有 for item in generator
的情况下使用它 。例如,我想将它与 while 语句(或其他构造)一起使用。我该怎么做?
最佳答案
内置函数
next(iterator[, default])
Retrieve the next item from the iterator by calling its__next__()
method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
在 Python 2.5 及更早版本中:
raiseStopIteration = object()
def next(iterator, default=raiseStopIteration):
if not hasattr(iterator, 'next'):
raise TypeError("not an iterator")
try:
return iterator.next()
except StopIteration:
if default is raiseStopIteration:
raise
else:
return default
关于python - 是否有另一种调用 python 生成器的 next 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/500578/