标签云

微信群

扫码加入我们

WeChat QR Code

This question already has an answer here:

Why does this code:

#!/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)

produce:

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

I'm a beginner; I don't quite understand why a) it counts all the way up to 9.. acting as if it had run 9 times, which it probably did, but does yield restart the for loop each time it is run?


Check out the highest scoring Python question ever

2018年08月16日26分54秒

Think of yield like you would print. It sends the data elsewhere, but internal to your function will pick up exactly where it left off. You yield three times for each member of mylist, for a total of 9.

2018年08月16日26分54秒

wnnmaw I did, that's where i got part of the example. I think I may be getting it; each time it yields- it returns to the loop calling mygenerator, and when the loop calls the mygenerator generator, it resumes precisely after the previous yield statement left off and hits yield again, and returns to the loop calling the generator. For as long as yield returns a value, the loop calling it will continue. The value of i doesn't change until the loop within the createGenerator function restarts which is why i see alpha/beta/carotene 3 times each.

2018年08月15日26分54秒