Python yield statement - don't understand this works this way
本问题已经有最佳答案,请猛点这里访问。
为什么此代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #!/usr/bin/env python def createGenerator(): mylist = [ 'alpha', 'beta', 'carotene' ] for i in mylist: yield i,"one" yield i,"two" yield i,"three" mygenerator = createGenerator() counter = 0 for i in mygenerator: counter += 1 print counter print(i) |
生产:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 1 ('alpha', 'one') 2 ('alpha', 'two') 3 ('alpha', 'three') 4 ('beta', 'one') 5 ('beta', 'two') 6 ('beta', 'three') 7 ('carotene', 'one') 8 ('carotene', 'two') 9 ('carotene', 'three') |
我是一个初学者;我不太明白为什么a)它一直到9。就好像它已经运行了9次,可能是这样的,但yield是否会在每次运行时重新启动for循环?
因为循环中有3个yield语句,所以生成了三次
因此:
3乘以3等于9。
您的输出说明:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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()中执行以下行
1 2 3 | mylist = [ 'alpha', 'beta', 'carotene' ] for i in mylist: yield i,"one" |
第一个收益率回报率("alpha","one")。此时,执行返回到for循环并打印。在for循环的下一个迭代中,执行将从上一个yield开始返回到createGenerator()。执行以下行:
1 | yield i,"two" |
它返回("alpha"、"two"),并在for循环中打印。当生成器没有更多要返回的值时,当生成i="胡萝卜素"和"三"时,for循环结束。