Python yield
2019-01-17 本文已影响0人
Solomon_Xie
def fab(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
for n in fab(5):
print n
递归中使用yield
有时候yield就可以解决递归的问题,但是有时候解决不了,还是要用递归。然后递归的同时还想达到yield的效果,就需要动点脑子了。
def recursion(self, num):
result = num**2
yield result
if num < 100:
yield from self.recursion(result)
for rec in recursion(100):
print( rec )