don't understand this works this way

This question already has an answer here:

  • What does the “yield” keyword do? 36 answers

  • You're yielding alpha three times because you have 3 yield statements in your loop.

    Thus:

  • Loop will iterate over your 3 elements
  • For each element you will yield 3 times
  • 3 times 3 equals 9.

    Your output explained:

    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 because the loop has in fact run 9 times.

    what's happening is that every time next() is called on the generator it continues execution after the previous yield.

    the first time next() is called the following lines are executed in createGenerator()

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

    The first yield returns ("alpha", "one"). At this point execution returns to the for loop and prints. In the next iteration of the for loop, execution returns to createGenerator() starting after the previous yield. The following line is executed:

    yield i, "two"
    

    Which returns ("alpha", "two") and prints in the for loop. The for loop ends when the generator has no more values to return, when i == "carotene" and "three" is yielded

    链接地址: http://www.djcxy.com/p/1556.html

    上一篇: 循环数据的收益率和收益率有什么不同

    下一篇: 不明白这种方式的作品