Python yield语句不理解这种方式

2024-10-02 22:30:50 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么这个代码:

#!/usr/bin/env python

def createGenerator():
    mylist = [ 'alpha', 'beta', 'carotene' ]
    for i in mylist:
        yield i, "one"
        yield i, "two"
        yield i, "three"
        print

mygenerator = createGenerator()

counter = 0
for i in mygenerator:
    counter += 1
    print counter
    print(i)

生产:

^{pr2}$

我是个初学者;我不太明白为什么a)它一直到9。。好像它已经运行了9次,很可能是这样,但是每次运行for循环时,yield都会重新启动它吗?在


Tags: 代码inalphaenvforbinusrdef
2条回答

因为循环中有3个yield语句,所以产生了alpha三次。在

因此:

  1. 循环将迭代3个元素
  2. 对于每一个元素,你将得到3次

3乘以3等于9。在

您的输出说明:

1                        <  counter
('alpha', 'one')         <  first yield statement
2                        <  counter
('alpha', 'two')         <  second yield statement
3                        <  counter
('alpha', 'three')       <  third yield statement
                         <  print statement in loop in function
4                        <  counter
('beta', 'one')          <  first yield statement, second iteration of loop
5                        <  counter
('beta', 'two')          <  second yield statement
6                        <  counter
('beta', 'three')        <  third yield statement
                         <  print statement in loop in function
7                        <  counter
('carotene', 'one')      <  first yield statement, third iteration of loop
8                        <  counter
('carotene', 'two')      <  second yield statement
9                        <  counter
('carotene', 'three')    <  third yield statement
                         <  print statement in loop in function

i=9,因为循环实际上已经运行了9次。在

所发生的是,每次在生成器上调用next()时,它都会在上一次生成之后继续执行。在

第一次调用next()时,在createGenerator()中执行以下行

mylist = [ 'alpha', 'beta', 'carotene' ]
    for i in mylist:
        yield i, "one"

第一个收益率回报(“α”,“一”)。此时,执行返回到for循环并打印。在for循环的下一次迭代中,执行返回到createGenerator(),从上一次生成之后开始。执行以下行:

^{pr2}$

返回(“alpha”,“two”)并在for循环中打印。当生成器没有更多的值要返回时,for循环结束,当i==“carbonote”和“three”被生成时

相关问题 更多 >