python3使用了更多内存优化的技巧,比如,python3的zip就是生成可迭代的对象

问题说明:

以前在使用zip(a,b)时,a,b都是一个非常大的list。使用python2解释器时,执行zip(a,b)都会提示,内存错误。后来找到了原因,python2的zip(a,b)直接是生成一个新的list,也就是说,把a,b拼在一起,然后全部载入内存。这是非常耗内存的。

但是python3已经改变了这种做法,python3生成的是可迭代的对象,并不是直接生成一个完整的list。降低内存的使用率。

下面举例说明这个问题:

Howto use Python's enumerate and zip to iterate over two lists and their indices.

alist = ['a1', 'a2', 'a3']
blist = ['b1', 'b2', 'b3']
for i, (a, b) in enumerate(zip(alist, blist)):
    print i, a, b

python2 和 python3比较,python3的很多函数生成了可迭代对象(zip),降低内存的使用率。

       In Python 3.x,range returns a range object instead of a list like it did in Python2.x. Similarly,zip now returns a zip object instead of a list.

While it may seem unhelpful at first, this change in the behavior of range and zip actually increases efficiency. This is because the zip and range objects produce items as they are needed,instead of creating a list to hold them all at once. Doing so saves on memory consumption and improves operation speed.zip产生的是生成器,可以按需生成数据,而不是直接将全部的数据生成,载入内存。可以提高速度和节约内存的使用率。

python2的zip,range直接生成最终结果,全部要载入内存。

总结:python3的zip,range生成的是可迭代的对象,按需获取数据,不需全部载入内存,提高速度,减少内存的使用率。python2的range和map直接生成最后结果。python3的做法优于python2。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值