加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 为什么我的生成器没有返回值?

发布时间:2020-12-20 12:04:51 所属栏目:Python 来源:网络整理
导读:我在 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生成器中遇到了一些令人惊讶的行为:

>>> 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

如果你真的,真的很想要.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读