首页 > 编程语言 > 详细

python_xrange和range的异同

时间:2014-03-24 17:52:50      阅读:531      评论:0      收藏:0      [点我收藏+]

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一样,所不同的是生成的不是一个数组而是一个生成器

代码示例:

bubuko.com,布布扣
>>> 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]
bubuko.com,布布扣

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.”

代码示例:

bubuko.com,布布扣
>>> 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

bubuko.com,布布扣

所以,在Range的方法中,它会生成一个list的对象,但是在XRange中,它生成的却是一个xrange的对象。当返回的东西不是很大的时候,或者在一个循环里,基本上都是从头查到底的情况下,这两个方法的效率差不多。但是,当返回的东西很大,或者循环中常常会被Break出来的话,还是建议使用XRange,这样既省空间,又会提高效率。

 

python_xrange和range的异同,布布扣,bubuko.com

python_xrange和range的异同

原文:http://www.cnblogs.com/graceting/p/3620314.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!