Python生成器

  1. 推导式创建生成器
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)

  1. 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)

posted @ 2021-03-10 10:54  code-G  阅读(71)  评论(0编辑  收藏  举报