Python生成器
- 推导式创建生成器
genter = (i * 2 for i in range(3))
# value = next(genter)
# print(value)
# value = next(genter)
# print(value)
# value = next(genter)
# print(value)
# value = next(genter)
# print(value)
# 取出的个数超过生成器的个数会报错,for循环会自动捕获异常
for i in genter:
print(i)
- yield创建生成器
def genter():
for i in range(3):
print('生成数据...')
yield i
print('上一个数据生成结束')
values = genter()
# value = next(values)
# print(value)
# value = next(values)
# print(value)
# value = next(values)
# print(value)
# value = next(values)
# print(value)
for value in values:
print(value)
示例:生成斐波那契数列
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
fi = fibonacci(10)
for value in fi:
print(value)