生成器小记
# !/usr/bin/python3# -*- coding: utf-8 -*-
# @Time : 2023/2/8 21:06
# @Author : xiongming
# @File : Shengchenqi.py
# @Desc : 生成器 - generator
# 生成器可以让函数退出之后,还保留状态
def counter():
i = 0
while i <= 3:
# yield 调用一次,提供一个数据,特殊迭代器。
yield i
i += 1
# 生成器对象 <generator object counter at 0x7fa56008dac0>
print(counter())
for i in counter():
print(i,end='、')
print()
# 斐波那契数列
def fib():
back1,back2 = 0, 1
while True:
yield back1
back1,back2 = back2,back1 + back2
print("-----分隔符1-------")
c = fib()
for i in range(10):
# next()函数获取
print(next(c),end='、')
print()
print("-----分隔符2-------")
# 生成器表达式
t = (i ** 2 for i in range(10))
for i in range(10):
print(next(t),end='、')
页:
[1]