''' 生成器generator建立 1.由列表生成式改寫 2.函數定義中有yield 生成器的調用方式 1.經過for調用 2.經過try except調用,而且得到返回值 ''' # l = [x*x for x in range(10)] ##[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # g = (x*x for x in range(10)) ##<generator object <genexpr> at 0x000001ABA974ED00> # print(l) # print(g) def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return 'done' ##for調用生成器 for n in fib(10): print(n) ##try except調用生成器(可提取返回值:Generator return value: done) g = fib(10) while True: try: x = next(g) print('g:',x) except StopIteration as e: print('Generator return value:',e.value) break
說明:內容來自於廖雪峯:https://www.liaoxuefeng.com/wiki/1016959663602400/1017318207388128函數
簡單總結:spa
生成器按需生產,節省內存空間。建立主要由列表生成式改寫和yield函數建立,調用方式主要有for循環和try...except,後者能夠提取返回值。code
##楊輝三角生成器 def triangles(max): n = 0 line = [1] while n<max: yield line line = [1]+[line[i]+line[i+1] for i in range(len(line)-1)]+[1] n+=1 return '楊輝三角運行完畢' for item in triangles(10): print(item)