文档章节

What does the yield keyword do in Python? (引用)

zshgss
 zshgss
发布于 2015/02/26 10:51
字数 449
阅读 10
收藏 0

When you create a list, you can read its items one by one, and it's called iteration:

>>> mylist = [1, 2, 3]>>> for i in mylist:...    print(i)123

Mylist is an iterable. When you use a list comprehension, you create a list, and so an iterable:

>>> mylist = [x*x for x in range(3)]>>> for i in mylist:...    print(i)014

Everything you can use "for... in..." on is an iterable: lists, strings, files... These iterables are handy because you can read them as much as you wish, but you store all the values in memory and it's not always what you want when you have a lot of values.

Generators

Generators are iterators, but you can only iterate over them once. It's because they do not store all the values in memory, they generate the values on the fly:

>>> mygenerator = (x*x for x in range(3))>>> for i in mygenerator:...    print(i)014

It is just the same except you used () instead of []. BUT, you can not perform for i in mygenerator a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end calculating 4, one by one.

Yield

Yield is a keyword that is used like return, except the function will return a generator.

>>> def createGenerator():...    mylist = range(3)...    for i in mylist:...        yield i*i...>>> mygenerator = createGenerator() # create a generator>>> print(mygenerator) # mygenerator is an object!<generator object createGenerator at 0xb7555c34>>>> for i in mygenerator:...     print(i)014

Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.

To master yield, you must understand that when you call the function, the code you have written in the function body does not run. The function only returns the generator object, this is a bit tricky :-)

Then, your code will be run each time the for uses the generator.

Now the hard part:

The first time the for calls the generator object created from your function, it will run the code in your function from the beginning until it hits yield, then it'll return the first value of the loop. Then, each other call will run the loop you have written in the function one more time, and return the next value, until there is no value to return.

The generator is considered empty once the function runs but does not hit yield anymore. It can be because the loop had come to an end, or because you do not satisfy a "if/else" anymore.


本文转载自:http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python

共有 人打赏支持
zshgss
粉丝 1
博文 1
码字总数 0
作品 0
青岛
程序员
转-深入探讨Ruby与Python语法比较

自:http://developer.51cto.com/art/200912/169306.htm 1. Ruby的case可以匹配很多东西:范围/数组,对象,正则表达,python没有case/switch而使用if/else比较死板点 2. python的缩进很漂亮...

玉龙
2011/10/12
0
0
Python中如何使用yield,对于庞大迭代的优化处理

一直困扰于yield的使用,今天看到一篇不错的解释,虽然都是英文,不过不要紧,可以跳开,直接看代码的部分就能懂 Improve Your Python: 'yield' and Generators Explained Posted on Apr 07...

青鸾之旅
2013/08/02
0
3
云计算Python自动化:Python标识符讲解

开发人员在程序中自定义的一些符号和名称。标示符是自己定义的,如变量名,函数名等。在日常生活中,标示符是用来指定某个东西、人,要用到它,他或她的名字;在数学中解方程时,我们也常常用到...

长沙千锋
05/15
0
0
如何理解yield--Python提高班

要想理解, 需要先理解(生成器), 要想理解, 需要先理解iterables(迭代器) iterables 先看这段代码: 这段代码的意思是list(列表)在python中是可以迭代的, 如果你需要一个接一个的访问一个数据集...

扑克
08/27
0
0
Python Tips, Tricks, and Hacks

一、快速技巧 1.1、4 种引号 ' ''' " """ print """I wish that I'd never heard him say, '''She said, "He said, 'Give me five dollars'"'''""" 1.2、对象/变量的真与假 my_object = 'Tes......

大数据之路
2013/07/23
0
0

没有更多内容

加载失败,请刷新页面

加载更多

你为什么在Redis里读到了本应过期的数据

一个事故的故事 晚上睡的正香突然被电话吵醒,对面是开发焦急的声音:我们的程序在访问redis的时候读到了本应过期的key导致整个业务逻辑出了问题,需要马上解决。 看到这里你可能会想:这是不...

IT--小哥
44分钟前
0
0
祝大家节日快乐,阖家幸福! centos GnuTLS 漏洞

yum update -y gnutls 修复了GnuTLS 漏洞。更新到最新 gnutls.x86_64 0:2.12.23-22.el6 版本

yizhichao
昨天
3
0
Scrapy 1.5.0之选择器

构造选择器 Scrapy选择器是通过文本(Text)或 TextResponse 对象构造的 Selector 类的实例。 它根据输入类型自动选择最佳的解析规则(XML vs HTML): >>> from scrapy.selector import Sele...

Eappo_Geng
昨天
2
0
Windows下Git多账号配置,同一电脑多个ssh-key的管理

Windows下Git多账号配置,同一电脑多个ssh-key的管理   这一篇文章是对上一篇文章《Git-TortoiseGit完整配置流程》的拓展,所以需要对上一篇文章有所了解,当然直接往下看也可以,其中也有...

morpheusWB
昨天
3
0
中秋快乐!!!

HiBlock
昨天
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部