问题说明:
以前在使用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。