博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python range 和 xrange 区别
阅读量:5094 次
发布时间:2019-06-13

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

引自 python官方文档 

  range
(
stop
)
  range
(
start
stop
[
step
]
)

This is a versatile function to create lists containing arithmetic progressions. It is most often used in  loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largeststart + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stopstep must not be zero (or else  is raised). Example:

>>> range(10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> range(1, 11)[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> range(0, 30, 5)[0, 5, 10, 15, 20, 25]>>> range(0, 10, 3)[0, 3, 6, 9]>>> range(0, -10, -1)[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]>>> range(0)[]>>> range(1, 0)[]
xrange
(
stop
)
xrange
(
start
stop
[
step
]
)

This function is very similar to , but returns an  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  over is minimal (since  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). For more information on xrange objects, see  and .

CPython implementation detail:  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. If a larger range is needed, an alternate version can be crafted using the module: islice(count(start, step), (stop-start+step-1+2*(step<0))//step).

 

官方文档中说明range返回的是一个list,而xrange返回的是一个xrange对象,并且xrange更加简洁快速,所以在程序当中应当尽量使用xrange。

转载于:https://www.cnblogs.com/jeesezhang/p/3542865.html

你可能感兴趣的文章
tomcat 后台启动设置
查看>>
react-music React全家桶项目,精品之作!
查看>>
结对-结对编项目作业名称-开发环境搭建过程
查看>>
怎样在Dos里切换盘符
查看>>
异常来自 HRESULT:0x800A03EC
查看>>
jQuery中使用$.ajax提交表单
查看>>
软件工程课堂作业(二)续——升级完整版随机产生四则运算题目(C++)
查看>>
js正则表达式及代码
查看>>
淘宝网络框架tbnet源码分析
查看>>
Laravel自学第一课:laravel下载与安装
查看>>
大数据调度工具azkaban的任务调度执行操作
查看>>
TOMCAT:对页面进行压缩从而节省网站的带宽以及提升用户的访问速度
查看>>
NSTimer的使用
查看>>
开学测试代码
查看>>
vue路由传参
查看>>
20181122_任务
查看>>
emacs使用指南
查看>>
Quartz.NET 任务调度新教程
查看>>
WPF 中对启动参数的处理
查看>>
如何查看MySQL的当前存储引擎?
查看>>