找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 2312|回复: 2

[求助] 求助一道yield、python、for语句综合题目

3

主题

4

帖子

4

积分

贫民

积分
4
疯子.py 发表于 2020-7-27 11:43:05 | 显示全部楼层 |阅读模式
def add(n,i):
    return n + i

def test():
    for i in range(4):
        yield i

g=test()
for n in [1,10]:
    g = (add(n,i) for i in g)

print(n)
print(list(g))

各位大佬,
输出应该是什么?
运行过程是怎样的?

回复

使用道具 举报

0

主题

6

帖子

6

积分

贫民

积分
6
阿姨不想洗铁路 发表于 2020-7-28 17:30:59 | 显示全部楼层
def add(n, i):
    return n + i


def test():
    for i in range(4):
        yield i


g = test()
for n in [1, 10]:
    # n = 1  时 g 相当于 (add(n, i0), add(n, n1), add(n, i2), add(n, i3))
    # n = 10 时 g 相当于 (add(n, add(n, i0)), add(n, add(n, i1)), add(n, add(n, i2)), add(n, add(n, i3)))
    g = (add(n, i) for i in g)

print(n)  # n = 10

#  i0 ~ i3 = 0 ~ 3
# g = (add(n, add(n, i0)), add(n, add(n, i1)), add(n, add(n, i2)), add(n, add(n, i3)))
print(list(g))  # list(g) = [20, 21, 22, 23]
回复 支持 反对

使用道具 举报

0

主题

956

帖子

956

积分

圣骑士

积分
956
sheeboard 发表于 2020-7-30 11:08:53 | 显示全部楼层
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表