生成器函数应用

在for循环中碰到yield会暂停本次循环,直到执行下一次__next__()才继续往下执行代码。

def test():
    for i in range(5):
        print('第%s次执行' % i)
        yield i
        print('开始新的循环')
g = test()
g.__next__()
# 第0次执行
g.__next__()
# 开始新的循环
# 第1次执行
g.__next__()
# 开始新的循环
# 第2次执行
g.__next__()
# 开始新的循环
# 第3次执行
next(g)
# 开始新的循环
# 第4次执行
g.__next__()
# 开始新的循环

实现嘀嗒函数

def tick():
    while 1:
        yield '嘀'
        yield '嗒'
g = tick()
print(g.__next__())
# 嘀
print(g.__next__())
# 嗒
print(g.__next__())
# 嘀
print(g.__next__())
# 嗒

统计班级人数占年纪人数百分比

eval可以将字符串转换成对应的数据类型
使用with打开文件不需要手动执行close
data.text:

{'class': 1, 'students': 30}
{'class': 2, 'students': 35}
{'class': 3, 'students': 28}
{'class': 4, 'students': 32}

get.py

def get_total():
    with open('data', 'r', encoding='utf-8') as f:
        for i in f:
            yield eval(i)['students']
g = get_total()
c1 = g.__next__()
c2 = g.__next__()
c3 = g.__next__()
c4 = g.__next__()
total = c1 + c2 + c3 +c4
print(c1 / total, c2 / total, c3 / total, c4 / total)
# 0.24 0.28 0.224 0.256

猜你喜欢

转载自blog.csdn.net/bus_lupe/article/details/84503684