您的位置:首页 > 编程语言 > Python开发

python_xrange和range的异同

2014-03-24 10:32 357 查看
1,range:

函数说明:range([start,]stop[,step]),根据start和stop的范围以及步长step生成一个序列

代码示例:

>>> range(5)
[0, 1, 2, 3, 4]
>>> range(2,5)
[2, 3, 4]
>>> range(2,5,2)
[2, 4]


2,xrange

函数说明:功能和range一样,所不同的是生成的不是一个数组而是一个生成器

代码示例:

>>> xrange(5)
xrange(5)
>>> list(xrange(5))
[0, 1, 2, 3, 4]
>>> xrange(2,5)
xrange(2, 5)
>>> list(xrange(2,5))
[2, 3, 4]
>>> xrange(2,5,2)
xrange(2, 6, 2)  #注意和range(2,5,2)的区别
>>> list(xrange(2,5,2))
[2, 4]


3,主要区别: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.”

代码示例:

>>> a = range(0,10)
>>> print type(a)
<type 'list'>
>>> print a[1],a[2]
1 2
>>> a2 = xrange(0,10)
>>> print type(a2)
<type 'xrange'>
>>> print a2[1],a2[2]
1 2


所以,在Range的方法中,它会生成一个list的对象,但是在XRange中,它生成的却是一个xrange的对象。当返回的东西不是很大的时候,或者在一个循环里,基本上都是从头查到底的情况下,这两个方法的效率差不多。但是,当返回的东西很大,或者循环中常常会被Break出来的话,还是建议使用XRange,这样既省空间,又会提高效率。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: