标签:提取 code color except done 内容 while one triangle
‘‘‘ 生成器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
简单总结:
生成器按需生产,节省内存空间。创建主要由列表生成式改写和yield函数创建,调用方式主要有for循环和try...except,后者可以提取返回值。
##杨辉三角生成器 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)
标签:提取 code color except done 内容 while one triangle
原文地址:https://www.cnblogs.com/liuhuacai/p/12304988.html