【问题标题】:How to solve StopIteration error in Python?如何解决 Python 中的 StopIteration 错误?
【发布时间】:2018-10-08 17:02:29
【问题描述】:

我刚刚阅读了一堆关于如何在 Python 中处理 StopIteration 错误的帖子,我在解决我的特定示例时遇到了麻烦。我只想用我的代码打印出 1 到 20,但它会打印出错误 StopIteration。我的代码是:(我是这里的新手,所以请不要阻止我。)

def simpleGeneratorFun(n):

    while n<20:
        yield (n)
        n=n+1
    # return [1,2,3]

x = simpleGeneratorFun(1)
while x.__next__() <20:
    print(x.__next__())
    if x.__next__()==10:
        break

【问题讨论】:

    标签: python while-loop conditional-statements generator break


    【解决方案1】:

    任何时候你使用x.__next__(),它都会得到下一个产生的数字——你不会检查每一个产生的数字并且跳过10——所以它会在20之后继续运行并中断。

    修复:

    def simpleGeneratorFun(n):
    
        while n<20:
            yield (n)
            n=n+1
        # return [1,2,3]
    
    x = simpleGeneratorFun(1)
    while True:
        try:
            val = next(x) # x.__next__() is "private", see @Aran-Frey comment 
            print(val)
            if val == 10:  
                break
        except StopIteration as e:
            print(e)
            break
    

    【讨论】:

    • 请使用next函数而不是__next__
    • 感谢您的回答和课程。我努力学习。
    • 我尝试了下一个,但它说:“AttributeError: 'generator' object has no attribute 'next'”
    • @BarishAhsen 将代码完全复制到pyfiddle.io - 选择 2.7 或 3.x - 两者都适用。如果它不适合您,请详细说明。你可能抄错了什么。
    【解决方案2】:

    首先,在每次循环迭代中,通过对__next__() 进行 3 次单独调用,您将迭代器推进 3 次,因此 if x.__next__()==10 可能永远不会被命中,因为第 10 个元素可能已被更早地使用。与缺少您的 while 条件相同。

    其次,python 中通常有更好的模式,您不需要直接调用next。例如,如果您有有限迭代器,请使用 for 循环在 StopIteration 上自动中断:

    x = simpleGeneratorFun(1)
    for i in x:
        print i
    

    【讨论】:

    • 感谢您的回答和教训。我记下了你的教程。
    猜你喜欢
    • 1970-01-01
    • 2013-06-23
    • 2016-08-05
    • 2017-12-17
    • 1970-01-01
    • 2016-11-20
    • 2023-04-02
    • 2020-10-31
    • 1970-01-01
    相关资源
    最近更新 更多