Python yield 小结和实例
时间:2023-07-21 15:37:39
一个带有 yield 的函数就是一个 generator,它和普通函数不同,生成一个 generator 看起来像函数调用,但不会执行任何函数代码,直到对其调用 next()(在 for 循环中会自动调用 next())才开始执行。虽然执行流程仍按函数的流程执行,但每执行到一个 yield 语句就会中断,并返回一个迭代值,下次执行时从 yield 的下一个语句继续执行。看起来就好像一个函数在正常执行的过程中被 yield 中断了数次,每次中断都会通过 yield 返回当前的迭代值。
yield 的好处:把一个函数改写为一个 generator 就获得了迭代能力,比起用类的实例保存状态来计算下一个 next() 的值,不仅代码简洁,而且执行流程异常清晰。
测试代码:
#!/usr/bin/env python
#-*- coding:utf8 -*-
def fab(max):
"""斐波那契數列"""
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n += 1
def perm(items, n=None):
"""全排列"""
if n is None:
n = len(items)
for i in range(len(items)):
v = items[i:i+1]
if n == 1:
yield v
else:
rest = items[:i] + items[i+1:]
for p in perm(rest, n-1):
yield v + p
if __name__ == '__main__':
for n in fab(5):
print n
print "全排列:123"
for n in perm("123"):
print n
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python3之文件读写操作的实例讲解
Vue为何弃用Ajax,选择Axios?ajax与axios的区别?
Go Ginrest实现一个RESTful接口
验证码的最高境界
![](https://img.aspxhome.com/file/UploadPic/20085/8/200858142214740s.png)
Div+CSS网页布局对SEO的影响漫谈
php面向对象程序设计
鼠标驱动图片变化
python如何查看系统网络流量的信息
快速排序的算法思想及Python版快速排序的实现示例
使用python 进行区间取值的方法
![](https://img.aspxhome.com/file/2023/4/70114_0s.png)
vue实现百度搜索下拉提示功能实例
![](https://img.aspxhome.com/file/2023/0/132900_0s.png)
Mysql中的自连接问题
![](https://img.aspxhome.com/file/2023/8/76358_0s.png)
Python数据分析库pandas高级接口dt的使用详解
![](https://img.aspxhome.com/file/2023/9/118609_0s.jpg)
分享4个Python中的非常好用的自动化脚本
![](https://img.aspxhome.com/file/2023/7/69467_0s.png)
内容为空时提交如何处理
![](https://img.aspxhome.com/file/UploadPic/20097/17/twitter-400x94-35s.gif)
JavaScript实现Tab标签页切换的最简便方式(4种)
![](https://img.aspxhome.com/file/2023/0/136260_0s.jpg)
JavaScript window.setTimeout() 的详细用法
web标准:CSS clear的属性及使用方法
Python连接MySQL数据库的简单便捷方法
![](https://img.aspxhome.com/file/2023/7/124367_0s.png)