python生成器学习:
案例分析一:
def demo():
for i in range(4):
yield i
g=demo()
g1=(i for i in g) #(i for i in demo())
g2=(i for i in g1) #(i for i in (i for i in demo())) --->
print(list(g1)) #list((i for i in demo())) #执行后 list((0,1,2,3)) --->[0,1,2,3]
print(list(g2)) #因为g1生成器(i for i in demo())已经使用,所有为空(),--->g2=(i for i in ())=()--->所以list(g2)=[]
--------结果:
[0, 1, 2, 3]
[]
案例分析二:
def add(n,i):
return n+i
def test():
for i in range(4):
yield i
g=test() # (i for i in range(4))
for n in [1,10]:
g=(add(n,i) for i in g)#
print(list(g))
-----------结果:
[20, 21, 22, 23]
#解析:
-------
n=1
g=(add(n+i)for i in (i for i in range(4)) )
n=10
g=(add(n+i)for i in (add(n+i)for i in (i for i in range(4)) ) )
g:(add(n+i)for i in (add(n+i)for i in (0,1,2,3) ) )
--->n=10 解:
--->g=(add(10+i)for i in (add(10+i)for i in (0,1,2,3) ) )
--->g=(add(10+i)for i in (10,11,12,13) )
--->g=(20,21,22,23)
--->list(g)=[20,21,22,23]