python - 是否有另一种调用 python 生成器的 next 方法?

标签 python language-features

我有一个生成器,我想知道我是否可以使用它而不必担心 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/

相关文章:

python - 如何在 Airflow 中通过 SSH 并运行 PythonOperator

python - KNeighborsClassifier .predict() 函数不起作用

java - java中的interface和@interface有什么区别?

java - 值类型的 asInstanceOf[X] 和 toX 之间有什么区别吗?

Java 语言规范 : LambdaExpression in Java ConditionalExpression

c# - I可用 : controlling resources in a better way than IDisposable

python - render_template() 恰好接受 1 个参数

Python:处理字符串时出现问题

python - tkinter 中不断更新图表

c# - 被拳击迷惑。将 -1 转换为 Int64 会抛出 InvalidCastException