python - 生成器的Python生成器
问题描述
这是我在面试时遇到的一个问题(python 3.7):
def add(x,y):
return x+y
g = (x for x in range(4))
for n in [1,10]:
g = (add(n,i) for i in g)
list(g)
list(g) 打印什么?答案是
20,21,22,23
从输出中,我猜发生了什么是 add 函数循环了两次,并且两次都 n=10?有人可以向我解释一步一步会发生什么吗?我感到很困惑。非常感谢。
解决方案
The "body" of a generator expression does not capture values in a closure, so n
is just a free variable whose value is whatever is assigned to n
once g
is evaluated. (The expression iterated over is, so g
is not a free variable, but the iterable currently assigned to g
.)
That is, after for
loop, you have
assert n == 10 # The last value assigned to n
# Pseudocode - every time n is used, it resolves to the *current*
# value of n, not the value n had when the generator expression was
# defined.
g = (add(10, i) for i in (add(10, i) for i in (x for x in range(4))))
# *not* (add(10, i) for i in (add(1, i) for i in (x for x in range(4))))
= (add(10, i) for i in (add(10, i) for i in (0, 1, 2, 3)))
= (add(10, i) for i in (10, 11, 12, 13))
= (10 + i for i in (10, 11, 12, 13)
And so
list(g) == [20, 21, 22, 23]
推荐阅读
- python - 使用输入while循环python的最大和最小数字
- aws-lambda - 无服务器框架和 AWS Lambda 函数代码
- vim - Vim 以 REPLACE 模式打开,添加 'set noesckeys' 使箭头键无法使用
- .htaccess - 使用 htaccess 重写搜索 URL
- excel - “工作簿”对象没有属性“单元格”?我需要帮助将数据列表导出到另一个 Excel 文件
- reactjs - wordpress 可以做复杂的事情,比如反应吗?
- javascript - Express 和 mongoose 应用程序在一条路线低于另一条路线时出现错误 404,但在其上方时有效
- c# - 更改excel折线图中系列的颜色
- javascript - 我的 React 应用程序中有按钮和教科书,如何使单击按钮触发文本输入?
- java - Java 静态方法与验证器中的单例