首页 > 解决方案 > 生成器的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?有人可以向我解释一步一步会发生什么吗?我感到很困惑。非常感谢。

标签: pythongenerator

解决方案


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]

推荐阅读