相当于一种动态加载的形式,比如我们求一个斐波那契数列,这个是一个无限长度的序列,使用列表肯定放不下,所以可以使用生成器来解决。
def fib(max):
a, b = 0, 1
for _ in range(max):
yield b
a, b = b, a + b
return 'done'
这个fib函数就变成了一个generator,是一个可迭代对象
print(fib(10))
#输出<generator object fib at 0x7f8f96e5deb8>
可以把它当成一个列表访问
for x in fib(10):
print(x)
#输出1 1 2 3 5 8 13 21 34
这里,最难理解的就是generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。
可以使用next函数来访问
def test():
yield 1
yield 2
yield 3
t = test()
print(next(t))#output:1
print(next(t))#output:1
print(next(t))#output:1
print(next(t))#output
利用生成器生成杨辉三角
def triangle():
_list, new_list = [1], []
while True:
if len(_list)==1:
yield new_list
for times in range(len(_list)):
if times == 0:
new_list.append(1)
else:
temp = _list[times - 1] + _list[times]
new_list.append(temp)
new_list.append(1)
yield new_list #返回值,然后挂起函数,等待下一次调用
_list = new_list.copy()#调用后会继续执行下去
new_list.clear()
n = 0
for result in triangle():
n += 1
print(result)
if n == 10:
break