0
def prefixes(s):
    if s:
        yield from prefixes(s[:-1])
        yield s

t = prefixes('both')
next(t)

下一个(t)返回'b'。我只是对为什么会这样感到困惑,因为如果我们遵循yield from声明,我们最终yield from prefixes('')会以返回 None 结束。在我的所有其他测试中,从 None 产生的结果会引发 TypeError。相反,这似乎只是被忽略了,并且 prefixes('b') 移动到下一个 yield 语句(?为什么这样做?)以产生 'b'...关于为什么的任何想法?将不胜感激解释。

4

2 回答 2

0

发电机是惰性(按需)对象,你没有用尽你的发电机t,你可以使用你的发电机:

list(t)
# ['b', 'bo', 'bot', 'both']

现在如果你使用next(t)你会得到预期的StopIteration

StopIteration                             Traceback (most recent call last)
<ipython-input-25-680ef78477e2> in <module>
      6 t = prefixes('both')
      7 list(t)
----> 8 next(t)

StopIteration: 

if声明是“保证”你有一个结束,你永远不会None[:-1]做得到TypeError

于 2020-04-19T16:13:21.030 回答
0

prefixesStopIteration包装在一个生成器中,该生成器在函数返回时引发。当传递一个空字符串时,prefixes跳过任何 yield,到达其代码块的末尾并返回,导致StopIteration. 返回值无所谓,丢弃

>>> next(prefixes(""))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

yield from抑制内部生成器StopIteration并让外部生成器继续。

于 2020-04-19T16:23:55.423 回答