Python中两个连续的yield语句如何工作? [英] How two consecutive yield statement work in python?

查看:553
本文介绍了Python中两个连续的yield语句如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在合并和拆分部分的 pymotw.com 中偶然发现了此代码.

I stumble upon this code from pymotw.com in merging and splitting section.

from itertools import *


def make_iterables_to_chain():
    yield [1, 2, 3]
    yield ['a', 'b', 'c']


for i in chain.from_iterable(make_iterables_to_chain()):
    print(i, end=' ')
print()

我不明白make_iterables_to_chain()的工作方式.它包含两个yield语句,它如何工作? 我知道生成器是如何工作的,但是在那里,但是只有一个 yield 语句.

I can not understand how make_iterables_to_chain() is working. It contains two yield statement, how does it work? I know how generators work but there but there was only single yield statement.

请帮助!

推荐答案

与单个yield的工作方式相同.

The same way a single yield works.

在生成器中可以有任意多个yield,当在其上调用__next__时,它将一直执行直到遇到下一个收益.然后,您会返回产生的表达式,并且生成器会暂停直到再次调用它的__next__方法.

You can have as many yields as you like in a generator, when __next__ is called on it, it will execute until it bumps into the next yield. You then get back the yielded expression and the generator pauses until it's __next__ method is invoked again.

在生成器上运行几个next调用以查看此内容:

Run a couple of next calls on the generator to see this:

>>> g = make_iterables_to_chain()  # get generator
>>> next(g) # start generator, go to first yield, get result
[1, 2, 3]
>>> next(g) # resume generator, go to second yield, get result
['a', 'b', 'c']
>>> # next(g) raises Exception since no more yields are found 

这篇关于Python中两个连续的yield语句如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆