【发布时间】:2015-08-05 23:42:18
【问题描述】:
有人能解释一下其中的每个步骤是做什么的吗?
我从未见过“for i in X:”在 X 是生成器的情况下使用,如果 i 没有插入 () 之间,我无法理解它是如何与函数交互的。
def fib():
a, b = 0,1
while True:
yield b
a,b = b, a + b
for i in fib():
print(i)
【问题讨论】:
有人能解释一下其中的每个步骤是做什么的吗?
我从未见过“for i in X:”在 X 是生成器的情况下使用,如果 i 没有插入 () 之间,我无法理解它是如何与函数交互的。
def fib():
a, b = 0,1
while True:
yield b
a,b = b, a + b
for i in fib():
print(i)
【问题讨论】:
for loop 如果您像上面那样使用它,则会生成一次性变量。例如,list object 在循环中反复使用,但一次性迭代器在使用后会自动删除。
而yield 是一个类似return 的术语,用于函数中。它给出一个结果并在循环中再次使用它。
您的代码为您提供了称为斐波那契的数字。
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.
【讨论】:
要理解这一点,您必须了解 yield 关键字的作用。请看这个:What yield does?
现在你知道fib() 不是一个函数,它是一个生成器。
所以在代码中:
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)
因为While 永远不会得到错误值。它一直在运行。
【讨论】: