python3 生成器表达式

时间:2021-07-12 14:12:03
生成器表达式
[i for i in range(100)]       #列表解析

 与列表解析的不同是,列表解析用中括号,生成器表达式用小括号

g = (i for i in range(1000))    #生成器表达式     #不用yield的表达形式

print(g)  #这是一个迭代对象
print(next(g)) #next(g) == g.__next__() #next(g)相当于g.__next__()
print(next(g)) #next(g) == g.__next__()
print(next(g)) #next(g) == g.__next__()
print(next(g)) #next(g) == g.__next__()
print(next(g)) #next(g) == g.__next__()

生成器表达式的应用:

# 列表解析
l = []
with open('goods', encoding='utf-8') as f:
l = [float(line.split()[1]) * int(line.split()[2]) for line in f]
print(sum(l)) # 生成器表达式
with open('goods', encoding='utf-8') as f:
g = (float(line.split()[1]) * int(line.split()[2]) for line in f)
print(sum(g)) # 换个方式
g = (float(line.split()[1]) * int(line.split()[2]) for line in open('goods', encoding='utf-8'))
print(sum(g))