生成器一,簡單spa
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))
生成器二,難一點的code
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)) print(list(g)) print(list(g))
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)) print(list(g)) print(list(g)) print(list(g))
分析簡單一blog
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)) # 只有list之後纔開始執行,以前都不執行, # 此時[0,1,2,3],g1再循環取值或list取值已經沒法取到, # 生成器迭代器只能執行一次 for n in g1: print(n) print(list(g2))
分析二難一點class
def add(n,i): return n+i def test(): for i in range(4): yield i g = test() # for n in [1,10,5]: # n = 1 # g = (add(n,i) for i in test()) # n = 10 # g = (add(n,i) for i in (add(n,i) for i in test())) n = 5 g = (add(n,i) for i in (add(n,i) for i in (add(n,i) for i in test()))) print(list(g)) print(list(g))