python生成器表达式

生成器表达式

相比列表表达式,将[]换成了(),返回对象不是一个列表,而是一个生成器,相比列表更加省内存

实例1:

列表表达式写法:

l = ['apple%s' % i for i in range(10000)]
print(l)

生成器表达式写法:

g = ('apple%s' % i for i in range(10000))
for i in g:
    print(i)

实例2:

一般写法:

res = []
with open('test1.txt') as f:
    for line in f:
        l = line.split(',')
        d = {}
        d['name'] = l[0]
        d['price'] = l[1]
        d['count'] = l[2]
        res.append(d)
        print(d)

生成器表达式写法:

with open('test1.txt') as f:
    res = (line.split(',') for line in f)
    dic_g = ({'name': i[0], 'price': i[1], 'count': i[2]} for i in res)
    apple_dic = next(dic_g)   #只有调用next才会往外拿一个,大大节省内存
    print(apple_dic)

 

posted on 2018-08-24 00:50  Messiless  阅读(326)  评论(0编辑  收藏  举报