Python中Range和XRange的区别


Python中Range和XRange的区别(Difference between Range and XRange in Python)

最近机器出了点问题,所以一直没有写新的东西出来。之前在读Python的代码的时候,发觉好多人喜欢用XRange,而不是Range,我也只是 记得学习的时候开始学到的是Range,后面又看到有个XRange,当时也没有深究,为什么Python里面要有两个同样的功能的系统函数。今天再去仔 细查了下文档,原来它们之间还是有点区别,虽然不是很大,但至少XRange的效率会比Range的高。

在文档中是这样写的:xrange([start,] stop[, step])This function is very similar to range(), but returns an ``xrange object'' instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of xrange() over range() is minimal (since xrange() still has to create the values when asked for them) except when a very large range is used on a memory-starved machine or when all of the range's elements are never used (such as when the loop is usually terminated with break).Note: xrange() is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs ("short" Python integers), and also requires that the number of elements fit in a native C long.
在Range的方法中,它会生成一个list的对象,但是在XRange中,它生成的却是一个 xrange的对象,当返回的东西不是很大的时候,或者在一个循环里,基本上都是从头查到底的情况下,这两个方法的效率差不多。但是,当返回的东西很大, 或者循环中常常会被Break出来的话,还是建议使用XRange,这样既省空间,又会提高效率。
下面举个例子:
如果使用range函数,执行下面的语句,将会得到后面的结果:
>>> a = range(0,100)

>>> print type(a)

>>> print a

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

>>> print a[0], a[1]

0 1

但是,将开始的range用xrange替换,将会得到不同的结果:
>>> a = xrange(0,100)

>>> print type(a)

>>> print axrange(100)

>>> print a[0], a[1]

0 1

这里可以很直接的看到它们的不同点,虽然a[0], a[1]返回的值是相同的。所以,以后coding的时候还是尽可能使用xrange了

相关内容