python生成器學習

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]
相關文章
相關標籤/搜索