• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python中yield什么意思

python 搞代码 4年前 (2022-01-09) 24次浏览 已收录 0个评论

python中yield什么意思?

可迭代对象

mylist 是一个可迭代的对象。当你使用一个列表生成式来建立一个列表的时候,就建立了一个可迭代的对象:

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

在这里,所有的值都存在内存当中,所以并不适合大量数据

生成器

可迭代

只能读取一次

实时生成数据,不全存在内存中

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

注意你之后不能再使用for i in mygenerator了

yield关键字

yield 是一个类似 return 的关键字,只是这个函数返回的是个生成器

当你调用这个函数的时候,函数内部的代码并不立马执行 ,这个函数只是返回一个生成器对象

当你使用for进行迭代的时候,函数中的代码才会执行

>>> 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)

第一次迭代中你的函数会执行,从开始到达 yield 关键字,然后返回 yield 后的值作为第一次迭代的返回值. 然后,每次执行这个函数都会继续执行你在函数内部定义的那个循环的下一次,再返回那个值,直到没有可以返回的。

控制生成器的穷尽

>>> class Bank(): # let's create a bank, building ATMs...    crisis = False...    def create_atm(self) :...        while not self.crisis :...            yield "$100">>> hsbc = Bank() # when everything's ok the ATM gives you as much as you want>>> corner_street_atm = hsbc.create_atm()>>> print(corner_street_atm.next())$100>>> print(corner_street_atm.next())$100>>> print([corner_street_atm.next() for cash in range(5)])['$100', '$100', '$100', &#39<em>本文来源[email protected]搞@^&代*@码)网5</em>;$100', '$100']>>> hsbc.crisis = True # crisis is coming, no more money!>>> print(corner_street_atm.next())<type 'exceptions.StopIteration'>>>> wall_street_atm = hsbc.create_atm() # it's even true for new ATMs>>> print(wall_street_atm.next())<type 'exceptions.StopIteration'>>>> hsbc.crisis = False # trouble is, even post-crisis the ATM remains empty>>> print(corner_street_atm.next())<type 'exceptions.StopIteration'>>>> brand_new_atm = hsbc.create_atm() # build a new one to get back in business>>> for cash in brand_new_atm :...    print cash$100$100$100$100$100$100$100$100$100...

相关推荐:《Python教程》

以上就是python中yield什么意思的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python中yield什么意思

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址