题目:

 def add(n,i):
return n+i def test():
for i in range(4):
yield i g = test()
for n in [1,10,5]:
g = (add(n,i) for i in g) print(list(g))

  分析:

  我们知道生成器函数和生成器表达式都很"懒",只要你不找它取值它就不执行.

  函数从上到下开始执行,一直到13行都没开始,13行list()函数找g要值,9-10行的生成器表达式才开始执行,我们将9-10行拆开:

 n =1
g = (add(n,i) for i in g)
n =10
g = (add(n,i) for i in g)
n =5
g = (add(n,i) for i in g)

  根据执行顺序,1-4行都是生成器表达式,在13行找此时6行要值的时候,1-4行都还未执行,我们将表达式都写在6行,得到:

 n =5
g = (add(n,i) for i in (add(n,i) for i in (add(n,i) for i in test())))

  从里面往外面执行,

  test() == (0,1,2,3)

  (add(n,i) for i in test()) == (5,6,7,8)

  (add(n,i) for i in (add(n,i) for i in test())) ==(10,11,12,13)

  (add(n,i) for i in (add(n,i) for i in (add(n,i) for i in test()) )) ==(15,16,17,18)

  g=(15,16,17,18)

  list(g) == [15,16,17,18]

  输出结果:

 [15, 16, 17, 18]
05-11 09:32