python - Why do I need to store generator function to a variable first?
问题描述
I am exploring the use of generators in python, but I'm running into a strange kind of issue.
How can it be that the following code works as expected (e.g. returns next fibonacci number every time function is called):
def fibonacci():
current, previous = 0,1
while True:
yield current
current, previous = current + previous, current
fib = fibonacci()
for i in range(0,21):
print(next(fib))
But when I directly call the function inside my for-loop, as such:
for i in range(0,21):
print(next(fibonacci()))
It prints out 21 zero's?
解决方案
正如克里斯在评论中所说:
因为那时您在每次迭代中都创建了新的生成器对象,一遍又一遍地获取第一个元素。
您可以通过直接迭代它来避免将其分配给变量。这样您只创建一个生成器对象:
for n, i in zip(fibonacci(), range(0,21)):
print(n)
推荐阅读
- r - 加入时使用 data.table on = .( ) 参数中的函数
- c++ - 运算符重载 >> 到复数
- flask - Flask 变量不适用于 console.log
- android - npx react-native run-android 失败并出现错误
- python - Azure 持久功能扇入/扇出自定义状态
- mysql - SQL 存储过程 - 我哪里出错了?
- node.js - 为什么我会收到此错误 TypeError: Cannot read property 'utf8Slice' of undefined
- powershell - 正则表达式在脚本中运行时不匹配,但在控制台中运行时匹配?
- python - Python:为什么拆分不能正确处理数字
- java - 尽管在测试中返回了一行,但 SQL ResultSet 为空