我在
Python生成器中遇到了一些令人惊讶的行为:
>>> def f(n):
... if n < 2:
... return [n]
... for i in range(n):
... yield i * 2
...
>>> list(f(0))
[]
>>> list(f(1))
[]
>>> list(f(2))
[0, 2]
为什么前两种情况下发电机没有返回任何值?
最佳答案 因为生成器返回语句不返回任何内容,所以它们结束执行(python知道这是一个生成器,因为它包含至少一个yield语句).而不是返回[n]做
yield n
return
编辑
在用python核心开发者提出这个问题后,他们向我指出了它所说的python docs
In a generator function, the return statement indicates that the generator is done and will cause StopIteration to be raised. The returned value (if any) is used as an argument to construct StopIteration and becomes the StopIteration.value attribute.
所以你可以做到
def f(n):
if n < 2:
return [n]
for i in range(n):
yield i * 2
g = f(1)
res = []
while True:
try:
res.append(next(g))
except StopIteration as e:
if e.value is not None:
res = e.value
break
如果你真的,真的很想要.