一、生成器的创建方式
生成器:根据算法生成数据的一种机制,每次调用生成器只生成一个值,可以节省大量内存
1. 生成器推导式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| my_generator = (i * 2 for i in range(5)) print(my_generator)
value = next(my_generator) print(value)
value = next(my_generator) print(value)
print('----------')
for value in my_generator: print(value)
|
2. yield 关键字
- 只要在def函数里面看到有 yield 关键字那么就是生成器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| def mygenerater(n): for i in range(n): print('开始生成...') yield i print('完成一次...')
if __name__ == '__main__':
g = mygenerater(5)
for i in g: print(i)
|
二、生成器的使用场景
1. 斐波那契数列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| def fibonacci(num): a = 0 b = 1
current_index = 0
while current_index < num: result = a a, b = b, a + b current_index += 1 yield result
fib = fibonacci(5)
for value in fib: print(value)
|