Python 中的发电机使用情况
Generator usage in Python
我正在学习生成器,所以我定义了以下计算斐波那契数列的函数:
def fib(max):
a, b = 0, 1
while a < max:
yield a
a, b = b, a + b
我试过这样使用它,但是没有用:
next(fib(10))
Out[413]: 0
next(fib(10))
Out[414]: 0
next(fib(10))
Out[415]: 0
但是,像这样使用它会按预期工作:
f = fib(10)
next(f)
Out[417]: 0
next(f)
Out[418]: 1
next(f)
Out[419]: 1
next(f)
Out[420]: 2
为什么第一种情况不行?
next(iterator[, default])
Retrieve the next item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
第一个有效:
它只是为您在调用fib(10)
时创建的每个函数实例生成一个新的iterator
因此,每次调用 fib(10)
时,您都会创建一个新的 fib 函数实例,该实例 return 是特定于该实例的 iterator
。
请注意,它们都 return 第一个值正确。
当你 运行 在第一种情况下它会从头开始重新开始,所以它总是会先开始 --> 而在第二种情况下每次你调用 f 时,f 都在改变所以它开始-->第一-->第二-->第三。
我正在学习生成器,所以我定义了以下计算斐波那契数列的函数:
def fib(max):
a, b = 0, 1
while a < max:
yield a
a, b = b, a + b
我试过这样使用它,但是没有用:
next(fib(10))
Out[413]: 0
next(fib(10))
Out[414]: 0
next(fib(10))
Out[415]: 0
但是,像这样使用它会按预期工作:
f = fib(10)
next(f)
Out[417]: 0
next(f)
Out[418]: 1
next(f)
Out[419]: 1
next(f)
Out[420]: 2
为什么第一种情况不行?
next(iterator[, default])
Retrieve the next item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
第一个有效:
它只是为您在调用fib(10)
iterator
因此,每次调用 fib(10)
时,您都会创建一个新的 fib 函数实例,该实例 return 是特定于该实例的 iterator
。
请注意,它们都 return 第一个值正确。
当你 运行 在第一种情况下它会从头开始重新开始,所以它总是会先开始 --> 而在第二种情况下每次你调用 f 时,f 都在改变所以它开始-->第一-->第二-->第三。