python print inside vs outside function?
本问题已经有最佳答案,请猛点这里访问。
下面的代码以前在末尾使用for循环打印了fibonacci。我在函数中移动了打印,然后调用了它,但尽管函数中有打印,但没有打印出斐波那契纽伯。不是吗?
1 2 3 4 5 6 7 8 | def fibon(n): a = b = 1 for i in range(n): yield a a, b = b, a + b print(a) # move here inside function but doesnt print? fibon(20) |
旧代码的工作方式:
1 2 | for x in fibon(100): print(x) |
简而言之,python生成器是迭代器。描述简单生成器的PEP 255。生成器可以通过对生成器对象调用下一个方法或在for循环中使用生成器对象来使用。
要执行生成器,需要对其进行迭代。因此,
1 2 3 4 5 6 7 8 9 10 11 12 13 | def fibon(n): a = b = 1 for i in range(n): yield a a, b = b, a + b fibon(5) <generator object fibon at 0x00000000034A6A20> for i in fibon(5): print i # list() can be used too, because it accepts generator as a param fibos = list(fibon(5)) |
如果只将
1 2 | >>> fibon <function fibon at 0x0000000002D31C88> |
在代码中,
1 2 3 4 5 6 7 | def fibon(n): a = b = 1 for i in range(n): a, b = b, a + b print(a) # move here inside function but doesnt print? fibon(20) |
或从生成器对象构造列表
1 2 3 4 5 6 7 8 | def fibon(n): a = b = 1 for i in range(n): yield a a, b = b, a + b print(a) # move here inside function but doesnt print? list(fibon(20)) |
如果目标只是打印数字,那么用