Home > Backend Development > Python Tutorial > What does yield mean in python?

What does yield mean in python?

藏色散人
Release: 2019-07-05 11:05:52
Original
8889 people have browsed it

What does yield mean in python?

python中yield什么意思?

可迭代对象

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

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

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

生成器

可迭代

只能读取一次

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

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

注意你之后不能再使用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)
Copy after login

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

控制生成器的穷尽

>>> class Bank(): # let&#39;s create a bank, building ATMs
...    crisis = False
...    def create_atm(self) :
...        while not self.crisis :
...            yield "$100"
>>> hsbc = Bank() # when everything&#39;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)])
[&#39;$100&#39;, &#39;$100&#39;, &#39;$100&#39;, &#39;$100&#39;, &#39;$100&#39;]
>>> hsbc.crisis = True # crisis is coming, no more money!
>>> print(corner_street_atm.next())
<type &#39;exceptions.StopIteration&#39;>
>>> wall_street_atm = hsbc.create_atm() # it&#39;s even true for new ATMs
>>> print(wall_street_atm.next())
<type &#39;exceptions.StopIteration&#39;>
>>> hsbc.crisis = False # trouble is, even post-crisis the ATM remains empty
>>> print(corner_street_atm.next())
<type &#39;exceptions.StopIteration&#39;>
>>> 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
...
Copy after login

相关推荐:《Python教程

The above is the detailed content of What does yield mean in python?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template