列表解析、生成器表达式、匿名函数

1 列表解析

1.1 缺点占内存

s="hello"
l=[1,2,3,4,5]
l1=[(i,j)for i in l for j in s]
print(l1)

运行结果:
[(1, 'h'), (1, 'e'), (1, 'l'), (1, 'l'), (1, 'o'), 
(2, 'h'), (2, 'e'), (2, 'l'), (2, 'l'), (2, 'o'),
(3, 'h'), (3, 'e'),(3, 'l'), (3, 'l'), (3, 'o'),
(4, 'h'), (4, 'e'), (4, 'l'), (4, 'l'), (4, 'o'),
(5, 'h'), (5, 'e'), (5, 'l'), (5, 'l'),(5, 'o')]

2 生成器表达式(声明式编程)

2.1 跟列表解析使用方式一样,只是把【】换成()不占内存,每次只会有一个值

#生成器表达式
# l=[]
# with open("a.txt") as f:
#     for i in f:
#         i=i.strip()
#         goods=i.split(" ")
#         res=float(goods[-1]*goods[-2])
#         l.append(res)

with open("a.txt") as f:
    g=(float(line.split()[-1])*float(line.split()[-2]) for line in f)
    print(sum(g))

 

posted @ 2017-04-30 03:43  丨孤家寡人  阅读(105)  评论(0编辑  收藏  举报