python中的yield详解
上篇我们说到了python中的return,它在程序函数中返回某个值,返回之后函数不在继续执行,彻底结束。那你知不知道在python中还有一种返回值的方法,那就是yield。带有yield的函数是一个迭代器,函数返回某个值时,会停留在某个位置,返回函数值后,会在前面停留的位置继续执行,直到程序结束。
yield的作用:返回一个可以用来迭代(for循环)的生成器,它的应用场景通常为一个需要返回一系列值的,含有循环的函数中。
一、迭代器
迭代器有两个基本的方法:创建迭代器iter()和访问迭代器next()。
可以直接作用于for循环的对象统称为可迭代对象:Iterable
一类是集合数据类型,如list、tuple、dict、set、str等;
一类是generator,包括生成器和带yield的generatorfunction
迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。
二、生成器
如果列表元素可以按照某种算法推算出来,可以在循环的过程中不断推算出后续的元素,这样就不必创建完整的list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器:generator。
三、yield:是一个生成器函数,返回的是一个迭代器
yield表达式:
defsquare():
forxinrange(4):
yieldx**2
square_gen=square()
forxinsquare_gen:
print(x)
实例:生成器函数
#包含yield关键字,就变成了生成器函数
#调用函数并不会执行语句
deffoo():
print('Starting.....')
whileTrue:
res=yield4
print("res:",res)
#下面调用函数并没有执行,可以先将后面的语句注释掉
#逐行运行代码观察效果
g=foo()
print("第一次调用执行结果:")
print(next(g))
print("*"*100)
print("第二次调用执行结果:")
print(next(g))
print("*"*100)
第一次调用执行结果:
Starting.....
4
********************************************************************
第二次调用执行结果:
res:None
4
********************************************************************
通过迭代器、生成器和yield的介绍,你对yield有所了解了吗?yield的运用离不开迭代器和生成器,迭代器和生成器的运行也离不开yield。
以上内容为大家介绍了python中的yield详解,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python中ndarray与list转换的方法
python中ndarray与list转换的方法在python数据类型中,list元素可以任意类型组合,而ndarray元素类型必须相同,但是ndarray可以更方便的对多维...详情>>
2023-11-10 08:51:14
python中OrdereDict如何使用?
python中OrdereDict如何使用?我们在对数据进行处理时,如果能够使它们保存顺序的排序,那么用起来会非常的便利。不过字典本身就是没有顺序的,...详情>>
2023-11-10 07:05:00
python中如何使用scipy.fftpack模块计算快速傅里叶变换?
python中如何使用scipy.fftpack模块计算快速傅里叶变换?在编程中,快速傅里叶变换是工程中非常有价值的一类算法,它可以将时域和频域的信号相互...详情>>
2023-11-10 05:50:23
zip()函数如何在python中遍历多个列表?
zip()函数如何在python中遍历多个列表?下面我们就python中zip的说明、语法、使用注意点进行讲解,然后带来遍历多个列表的实例。1、说明zip()函...详情>>
2023-11-10 05:38:33热门推荐
python concat函数有何用法?
沸python里函数装饰器怎么使用?
热如何实现python中的continue语句?
热python中的冒泡排序是什么?
新python中str函数是什么
如何使用python实现项目进度显示?
python中ndarray与list转换的方法
python复制文件的方法整理
Python中numpy数组如何添加元素
python有几种可视化图形库?
python中xlwings是什么?
python上下文管理器的基本介绍
Python自动化测试基础必备知识点一
python中OrdereDict如何使用?
技术干货






