python yield
来源:互联网 发布:ubuntu安装jdk eclipse 编辑:程序博客网 时间:2024/06/06 04:08
def fab(max): n, a, b = 0, 0, 1 while n < max: yield b # print b a, b = b, a + b n = n + 1
> for n in fab(5): ... print n ... 1 1 2 3 5
有 yield 的函数在 Python 中被称之为 generator(生成器)。
在 for 循环执行时,每次循环都会执行 fab 函数内部的代码,执行到 yield b 时,fab 函数就返回一个迭代值,下次迭代时,代码从 yield b 的下一条语句继续执行,而函数的本地变量看起来和上次中断执行前是完全一样的,于是函数继续执行,直到再次遇到 yield。
另一个 yield 的例子来源于文件读取。如果直接对文件对象调用 read() 方法,会导致不可预测的内存占用。好的方法是利用固定长度的缓冲区来不断读取文件内容。通过 yield,我们不再需要编写读文件的迭代类,就可以轻松实现文件读取:
def read_file(fpath): BLOCK_SIZE = 1024 with open(fpath, 'rb') as f: while True: block = f.read(BLOCK_SIZE) if block: yield block else: return
https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/
阅读全文
0 0
- python----yield
- Python yield
- python yield
- python yield
- python --yield
- Python yield
- Python -- yield
- python yield
- Python yield
- python yield
- Python yield
- python yield
- python --yield
- Python yield
- python yield
- Python yield
- Python - yield
- python yield
- 下拉菜单(垂直)
- 修改系统时间 ubuntu
- Linux pthread_create内存泄漏问题
- python 程序生成exe文件
- json与数据库
- python yield
- VIN码识别(车架号识别)在二手车交易中的应用
- event.target.propertyName和event.target.getAttribute("propertyName")区别
- Unity 截取360全景图、浏览全景图
- python 后台运行问题
- const 类型
- 错误:Component is part of the declaration of 2 modules
- socket shutdown
- 服务器搭建实践(一)centos7使用nginx+tomcat实现负载均衡