生成器表达式
day24
# 列表生成式,列表大的话占内存 l = ["agg%s" % i for i in range(20)] print(l) # 生成器表达式,迭代器省内存 g = ("agg%s" % i for i in range(20)) # print(g) # print(g.__next__()) # print(g.__next__()) for i in g: # 可通过for循环或next取值 print(i)
将文件中每一行首尾的空格去掉
a.txt 内容:
asdgdfg dgdfgfgfdhgfdhfgjgjgfd dffdhf dfgdfhfgdjdjgjhgjgh123456732 dgdfhsfhhgfhfdsdh dfhfghgfjfhgj fghjfghjhdfgggggggggggggggggggg
# 传统方式 f = open("a.txt") newf = [] for line in f: line = line.strip() newf.append(line) print(newf) f.close() # 列表生成式方式 f = open("a.txt") f1 = [line.strip() for line in f] print(f1) f.close() # 生成器表达式 f = open("a.txt") f2 = (line.strip() for line in f) # print(f2) # print(next(f2)) # print(next(f2)) for i in f2: print(i) f2.close() f11 = open("a.txt") g = (line.strip() for line in f11) l3 = list(g) # 转为列表来查看迭代器里的值 print(l3) f.close()
列表生成式和生成器表达式都是声明式编程,如同声明一个变量一样。
print(sum([1, 2, 3, 4, 5])) numb_g = (i for i in range(5)) print(sum(numb_g))
运行结果:
15 10
求文件b.txt中商品的费用总和
b.txt内容:
apple 10 3 tesla 100000 1 mac 3000 2 lenovo 30000 3 chicken 10 3
# 传统方式 money_list = [] with open("b.txt") as f: for line in f: goods = line.split() res = float(goods[-1]) * float(goods[-2]) money_list.append(res) print(money_list) print(sum(money_list)) # 生成器表达式方式 with open("b.txt") as f: g = (float(line.split()[-1]) * float(line.split()[-2]) for line in f) print(sum(g))
# 模拟数据库查询,传统方式,变成字典 product_list = [] with open("b.txt") as f: for line in f: line = line.split() pro_dict = {"name": line[0], "price": line[1], "count": line[2]} product_list.append(pro_dict) print(product_list) # 模拟数据库查询,生成表达式方式 with open("b.txt") as f: p_list = (line.split() for line in f) # 将每一行变为小列表放到元组 p_dirc = ({"name": i[0], "price": i[1], "count": i[2]} for i in p_list) # 将每一个小列表变为字典放到元组 apple_dict = p_dirc.__next__() # next获得一个字典元素 print(apple_dict) print(apple_dict["count"])
共有 0 条评论