What does “for i in generator():” do?
本问题已经有最佳答案,请猛点这里访问。
有人能解释一下每一步的作用吗?
我从来没有见过"for i in x":用于x是生成器的地方,如果函数不插入()之间,我无法理解i如何与函数交互。
1 2 3 4 5 6 7 | def fib(): a, b = 0,1 while True: yield b a,b = b, a + b for i in fib(): print(i) |
任何包含
当你跑步的时候:
1 2 | for i in fib(): print(i) |
运行发电机的实际机制是:
1 2 3 4 5 6 7 | _iterator = iter(fib()) while True: try: i = next(_iterator) except StopIteration: break print(i) |
如您所见,将为i变量分配在生成器上调用next()以获取下一个值的结果。
希望能让我明白我来自哪里——)
注意,虽然
如果像上面那样使用,
1 2 3 4 5 6 7 8 9 10 | 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. |
要理解这一点,您必须了解
现在您可以了解到,
1 2 3 4 5 6 7 | def fib(): a, b = 0,1 while True: yield b #from here value of b gets returned to the for statement a,b = b, a + b for i in fib(): print(i) |
因为