← 返回首页
Python3基础教程(二十一)
发表时间:2022-03-29 22:12:30
生成器

1.生成器

在Python中,一边循环一边计算的机制,称为生成器:generator。

2.为什么要有生成器

列表所有数据都在内存中,如果有海量数据的话将会非常耗内存。如:仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。如果列表元素按照某种算法推算出来,那我们就可以在循环的过程中不断推算出后续的元素,这样就不必创建完整的list,从而节省大量的空间。

简单一句话:我又想要得到庞大的数据,又想让它占用空间少,那就用生成器!

要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator。

实例:

# -*- coding: utf-8 -*-
# @Time : 2022/3/29 21:46
# @File : generator.py
# @Software : PyCharm

g = (x * x for x in range(10))

for e in g:
    print(e)

运行结果:

0
1
4
9
16
25
36
49
64
81

比如,著名的斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到: 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

斐波拉契数列可以使用生成器实现。

例如:

# -*- coding: utf-8 -*-
# @Time : 2022/3/29 21:46
# @File : generator.py
# @Software : PyCharm

def fact(number):
    n, a, b = 0, 0, 1
    while n < number:
        yield b
        a, b = b, a + b
        n = n + 1
    return 'Done'

g = fact(100)
print(g)

运行结果:

<generator object fact at 0x00000289127EEC70>

这就是定义generator的另一种方法。如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator函数,调用一个generator函数将返回一个generator。因此并不能得到数列第100项的结果。只能获得第100次next()的结果,才是第100项的结果。

改写如下:

# -*- coding: utf-8 -*-
# @Time : 2022/3/29 21:46
# @File : generator.py
# @Software : PyCharm

def fact(number):
    n, a, b = 0, 0, 1
    while n < number:
        yield b
        a, b = b, a + b
        n = n + 1
    return 'Done'


g = fact(100)


for num in range(99):
    next(g)

result = next(g)
print("第100项是:",result)

运行结果:

第100项是: 354224848179261915075