What does "for i in generator():" do?

This question already has an answer here:

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

  • for loop generates disposable variable if you use it like above. For example, a list object is used again and again in a loop but a disposable iterator is deleted automatically after use.

    And yield is a term like return which is used in functions. It gives a result and use it again in loop. Your codes give you the number known as fibonacci.

    def fib():
        a, b = 0,1 #initially a=0 and b=1
        while True: #infinite loop term.
            yield b #generate b and use it again.
            a,b = b, a + b #a and b are now own their new values.
    
    for i in fib(): #generate i using fib() function. i equals to b also thanks to yield term.
        print(i) #i think you known this
        if i>100:
            break #we have to stop loop because of yield.
    

    Any function that contains a yield will return a generator. The for-loop runs that generator to return values one at a time.

    When you run:

    for i in fib():
        print(i)
    

    The actual mechanics of running the generator are:

    _iterator = iter(fib())
    while True:
        try:
            i = next(_iterator)
        except StopIteration:
            break
        print(i)
    

    As you can see, the i variable is assigned the result of calling next() on the generator to get the next value.

    Hope that makes it clear where the i comes from :-)


    for just ranges over the vaue of the expression. If the expression calls a function, then its value is whatever is returned from the function, so the for ranges over the result of that function.

    Note that here though fib is not a function, it is a generator. It successively yields the value of each step.

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

    上一篇: 收益不起作用,但回报确实

    下一篇: “对于我在发电机()中:”做什么?