【目录】
一 、生成器和yield
1、什么是生成器
2、为何要有生成器
3、如何使用生成器
二、yield表达式应用
三 、三元表达式、列表生成式、生成器表达式
3.1 三元表达式
3.2 列表生成式
3.3 生成器表达式
>>> def my_range(start,stop,step=1): ... print(‘start...‘) ... while start < stop: ... yield start ... start+=step ... print(‘end...‘) ... >>> g=my_range(0,3) >>> g <generator object my_range at 0x104105678>
>>> g.__iter__ <method-wrapper ‘__iter__‘ of generator object at 0x1037d2af0> >>> g.__next__ <method-wrapper ‘__next__‘ of generator object at 0x1037d2af0>
>>> next(g) # 触发函数执行直到遇到yield则停止,将yield后的值返回,并在当前位置挂起函数 start... 0 >>> next(g) # 再次调用next(g),函数从上次暂停的位置继续执行,直到重新遇到yield... 1 >>> next(g) # 周而复始... 2 >>> next(g) # 触发函数执行没有遇到yield则无值返回,即取值完毕抛出异常结束迭代 end... Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
>>> for i in countdown(3): ... print(i) ... countdown start 3 2 1 Done!
【2020Python修炼记21】Python语法入门—生成器
原文:https://www.cnblogs.com/bigorangecc/p/12557917.html