StopIteration
错误信息
StopIteration
快速摘要
你 called 下一个() on iterator 那个有 否更多值 到 produce.
为什么发生
Calling 下一个() 也许多次数 on 有限 iterator
Calling 下一个() on already-exhausted generator
Manual iteration 使用下一个() 不使用检查 for exhaustion
最小示例
✗ 错误代码
it = iter([1, 2])
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # StopIteration✓ 修复代码
it = iter([1, 2])
print(next(it, None)) # 1
print(next(it, None)) # 2
print(next(it, None)) # None (default, no error)下一个(它, 默认) 返回默认相反的 raising StopIteration 当 iterator 是 exhausted.
如何诊断
检查如何许多次数下一个() 是 called 对比. iterator's 长度
Use for 循环相反的 manual 下一个() calls
Provide 默认到 下一个(iter, 默认) 到 avoid 错误
如何修复
Use for 循环相反的 manual 下一个() calls
通过默认到 下一个(): 下一个(iter, default_value)
Wrap 下一个() in try/except StopIteration
如何预防
Prefer for 循环 over manual 下一个() iteration
Use 下一个(iter, 默认) 当默认是 acceptable