博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python_xrange和range的异同
阅读量:4460 次
发布时间:2019-06-08

本文共 1643 字,大约阅读时间需要 5 分钟。

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)
>>> print a[1],a[2]1 2>>> a2 = xrange(0,10)>>> print type(a2)
>>> print a2[1],a2[2]1 2

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

 

 

转载于:https://www.cnblogs.com/graceting/p/3620314.html

你可能感兴趣的文章
运算符 AS和IS 的区别
查看>>
(转)详解C中volatile关键字
查看>>
easyui时的时间格式yyyy-MM-dd与yyyy-MM-ddd HH:mm:ss
查看>>
专题:动态内存分配----基础概念篇
查看>>
Codeforces Round #426 (Div. 2) (A B C)
查看>>
The Most Simple Introduction to Hypothesis Testing
查看>>
UVA10791
查看>>
P2664 树上游戏
查看>>
jQuery 停止动画
查看>>
Sharepoint Solution Gallery Active Solution时激活按钮灰色不可用的解决方法
查看>>
MyBatis Generator去掉生成的注解
查看>>
教你50招提升ASP.NET性能(二十二):利用.NET 4.5异步结构
查看>>
lua连续随机数
查看>>
checkstyle使用介绍
查看>>
history.js 一个无刷新就可改变浏览器栏地址的插件(不依赖jquery)
查看>>
会了这十种Python优雅的写法,让你工作效率翻十倍,一人顶十人用!
查看>>
二维码图片生成
查看>>
在做操作系统实验的一些疑问
查看>>
Log4J日志配置详解
查看>>
NameNode 与 SecondaryNameNode 的工作机制
查看>>