Python 2.X 中的 range 和 xrange 函数有什么区别? [英] What is the difference between range and xrange functions in Python 2.X?
本文介绍了Python 2.X 中的 range 和 xrange 函数有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
显然 xrange 更快,但我不知道为什么它更快(并且除了轶事之外没有证据表明它更快)或者除此之外还有什么不同
Apparently xrange is faster but I have no idea why it's faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about
for i in range(0, 20):
for i in xrange(0, 20):
推荐答案
在 Python 2.x 中:
range
创建一个列表,所以如果你执行range(1, 10000000)
它会在内存中创建一个带有9999999
的列表元素.
range
creates a list, so if you dorange(1, 10000000)
it creates a list in memory with9999999
elements.
xrange
是一个惰性求值的序列对象.
xrange
is a sequence object that evaluates lazily.
在 Python 3 中:
range
相当于 Python 2 的xrange
.要获取列表,您必须明确使用list(range(...))
.xrange
不再存在.
range
does the equivalent of Python 2'sxrange
. To get the list, you have to explicitly uselist(range(...))
.xrange
no longer exists.
这篇关于Python 2.X 中的 range 和 xrange 函数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文