Python 生成器以及应用

一、定义

可以理解为一种数据类型,这种数据类型自动实现了迭代器协议(其他的数据类型需要调用自己内置的__iter__方法),所以生成器就是可迭代对象

二、生成器的两种形式(Python有两种不同的方式提供生成器)

1.生成器函数:常规函数定义,但是,使用yield语句而不是return语句返回结果。yield语句一次返回一个结果,在每个结果中间,挂起函数的状态,以便下次重它离开的地方继续执行

  yield的功能:
    1 把函数的结果做生迭代器(以一种优雅的方式封装好__iter__,__next__)
    2 函数暂停与再继续运行的状态是由yield

复制代码

def func():
    print('first')
    yield 11111111
    print('second')
    yield 2222222
    print('third')
    yield 33333333
    print('fourth')


g=func()
print(g)
from collections import Iterator
print(isinstance(g,Iterator)) #判断是否为迭代器对象

print(next(g))
print('======>')
print(next(g))
print('======>')
print(next(g))
print('======>')
print(next(g))

for i in g: #i=iter(g)
    print(i)

  

yield与return的比较?
  相同:都有返回值的功能
  不同:return只能返回一次值,而yield可以返回多次值

2.生成器表达式:类似于列表推导,但是,生成器返回按需产生结果的一个对象,而不是一次构建一个结果列表

g=('egg%s' %i for i in range(1000))
print(g)
print(next(g))
print(next(g))
print(next(g))

with open('a.txt',encoding='utf-8') as f:
    # res=max((len(line) for line in f))
    res=max(len(line) for line in f)
    print(res)

print(max([1,2,3,4,5,6]))

with open('a.txt',encoding='utf-8') as f:
    g=(len(line) for line in f)
    print(max(g))
    print(max(g))
    print(max(g))

三、应用

# [{'name': 'apple', 'price': 333, 'count': 3}, ]文件内容
#通过生成器表达器完成对文件的读完跟操作
with open('db.txt',encoding='utf-8') as f:
    info=[{'name':line.split()[0],
      'price':float(line.split()[1]),
      'count':int(line.split()[2])} for line in f if float(line.split()[1]) >= 30000]
    print(info)

猜你喜欢

转载自blog.csdn.net/weixin_37887248/article/details/81286514