了解迭代器默认值

Understanding iterator default value

我无法理解为什么第三个 next(w) 执行,并且 StopIteration 异常在下一个而不是第三个引发。

根据我的理解,next(w) 应该在任何表达式用尽时引发 StopIteration,并且只要 next(y, 'b') 达到默认值,即 'b' .

为什么迭代器returns默认值两次?

x = iter(range(3))
y = iter(range(3))
w = ([next(y, "a"), next(y, "b")] for z in x)
try:
    print(next(w)) # -> prints [0, 1]
    print(next(w)) # -> prints [2, 'b']
    print(next(w)) # -> prints ['a', 'b']
    print(next(w)) # raise StopIteration
    print(next(w))
except:
    print("7") # -> prints '7'

Why does the iterator returns the default value twice?

迭代器 return 的默认值被调用的次数是多少,而不仅仅是两次。出现此问题是因为您定义 xw 如下:

x = iter(range(3))
y = iter(range(3))
w = ([next(y, "a"), next(y, "b")] for z in x)

您的 w 列表有 3 个条目(它遍历 x 中的 3 个元素),当您第四次调用 next(w) 时,它会抛出异常。尝试设置 x = iter(range(5)),您会发现现在可以调用 print(next(w)) 5 次。内部 next 次调用将 return 默认值调用多次。

确认一下,创建后直接输出w即可,可以看到内容:

x = iter(range(3))
y = iter(range(3))
w = ([next(y, "a"), next(y, "b")] for z in x)
list(w)

> [[0, 1], [2, 'b'], ['a', 'b']]