感谢以上诸位的指教,差不多明白了,但又发现一个新问题,就是next()这个是什么意思:
文档里说使用next或者for的时候,yield的值为none:
When the execution is resumed by calling one of the generator's methods, the function can proceed exactly as if the yield expression were just another external call. The value of the yield expression after resuming depends on the method which resumed the execution. If __next__() is used (typically via either a for or the next() builtin) then the result is None. Otherwise, if send() is used, then the result will be the value passed in to that method.
文档还给了一个例子:
>>> def echo(value=None):
... print("Execution starts when 'next()' is called for the first time.")
... try:
... while True:
... try:
... value = (yield value)
... except Exception as e:
... value = e
... finally:
... print("Don't forget to clean up when 'close()' is called.")
...
>>> generator = echo(1)
>>> print(next(generator))
Execution starts when 'next()' is called for the first time.
1
>>> print(next(generator))
None
next(generator)为什么是none,而不是接着上面的echo(1)继续计算呢?另外,主贴的例子里面也是用for,但输出并不是,none啊
【 在 ToSimplicity (致简) 的大作中提到: 】
: for x in y
: 这个y的要求是iterabled而不是非得是列表
: yield就是“给”,机器猫从口袋里掏东西,大雄问它要,它就拿一个,“给”,再问再给。。。。
: --
--
※ 修改:·HYNOS 于 Jun 18 09:22:28 2022 修改本文·[FROM: 182.102.145.*]
※ 来源:·水木社区
http://m.mysmth.net·[FROM: 182.102.145.*]
修改:HYNOS FROM 182.102.145.*
FROM 182.102.145.*