def demo(): for i in range(4): yield i g=demo() g1=(i for i in g) g2=(i for i in g1) print(list(g1)) print(list(g2))
运行结果:
[0, 1, 2, 3]
[]
面试题2
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(list(g))
运行结果
[20, 21, 22, 23]
讲解:上述代码中:
for n in [1,10]:
g=(add(n,i) for i in g)
此for循环可写成:
n = 1
g=(add(n,i) for i in g)
n = 10
g=(add(n,i) for i in g)
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) n = 1 g=(add(n,i) for i in g) n = 10 g=(add(n,i) for i in g) print(list(g))
当程序运行到print(list(g))语句时,程序才开始执行。
首先找g,找到g后逐一替换