【Python那些事儿之十】range()和xrange()
by Harrison Feng in Python
无论是range()还是xrange()都是Python里的内置函数。这个两个内置函数最常用在for循环中。例如:
- >>> for i in range(5):
- ... print i
- ...
- 0
- 1
- 2
- 3
- 4
- >>> for i in xrange(5):
- ... print i
- ...
- 0
- 1
- 2
- 3
- 4
- >>>
range()和xrange() 在Python 2里是两种不同的实现。但是在Python 3里,range()这种实现被移除了; 保留了xrange()的实现,且将xrange()重新命名成range()。
首先,我们来看Python 2里range()。它是一个内置函数,这个函数用于创建整数等差数列。因此它 常被用于for循环。下面是range()的官方帮助文档。
- Help on built-in function range in module __builtin__:
- range(...)
- range(stop) -> list of integers
- range(start, stop[, step]) -> list of integers
- Return a list containing an arithmetic progression of integers.
- range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
- When step is given, it specifies the increment (or decrement).
- For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
- These are exactly the valid indices for a list of 4 elements.
- (END)
从官方帮助文档,我们可以看出下面的特性: 1、内置函数(built-in) 2、接受3个参数分别是start, stop和step(其中start和step是可选的,stop是必需的) 3、如果没有指定start,默认从0开始(Python都是从0开始的) 4、如果没有指定step,默认step是1。(step不能是0,如果指定step为0,“ValueError: range() step argument must not be zero” 将会被抛出。 额外的特性: 1、当step为正数时,start应该小于stop,否则将生成[ ],即空数列。
- >>> range(-3)
- []
- >>> range(5, 1)
- []
- >>> range(1,1)
- []
2、当step为负数时,start应该大于stop,否则将生成[ ],即空数列。 这两个特性说明range()可以生成递增和递减的数列。 下面是range()生成数列的例子:
- >>> range(5)
- [0, 1, 2, 3, 4]
- >>> range(1,8,3)
- [1, 4, 7]
- >>> range(0, -10)
- []
- >>> range(0, -10, -2)
- [0, -2, -4, -6, -8]
- >>>
接下来看看xrange()。 xrange()虽然也是内置函数,但是它被定义成了Python里一种类型(type), 这种类型就叫xrange。我们从Python 2的interactive shell里很容易看到这点。
- >>> range
- <built-in function range>
- >>> xrange
- <type 'xrange'>
- >>>
我们再来看看xragne的官方帮助文档:
- Help on class xrange in module __builtin__:
- class xrange(object)
- | xrange(stop) -> xrange object
- | xrange(start, stop[, step]) -> xrange object
- |
- | Like range(), but instead of returning a list, returns an object that
- | generates the numbers in the range on demand. For looping, this is
- | slightly faster than range() and more memory efficient.
- |
- | Methods defined here:
- |
- | __getattribute__(...)
- | x.__getattribute__('name') <==> x.name
- |
- | __getitem__(...)
- | x.__getitem__(y) <==> x[y]
- |
- | __iter__(...)
- | x.__iter__() <==> iter(x)
- |
- | __len__(...)
- | x.__len__() <==> len(x)
- |
- | __reduce__(...)
- |
- | __repr__(...)
- | x.__repr__() <==> repr(x)
- |
- | __reversed__(...)
- | Returns a reverse iterator.
- |
- | ----------------------------------------------------------------------
- | Data and other attributes defined here:
- |
- | __new__ =
- | T.__new__(S, ...) -> a new object with type S, a subtype of T
- (END)
从文档里可以看出,xrange和range的参数和用法是相同的。只是xrange()返回的不再是一个数列,而是一个 xrange对象。这个对象可以按需生成参数指定范围内的数字(即元素)。由于xrange对象是按需生成单个的 元素,而不像range那样,首先创建整个list。所以,在相同的范围内,xrange占用的内存空间将更小,xrange 也会更快。实际上,xrange由于是在循环内被调用时才会生成元素,因此无论循环多少次,只有当前一个元素 占用了内存空间,且每次循环占用的都是相同的单个元素空间。我们可以粗略的认为,相同n个元素的话,range占 用的空间是xrange的n倍。因此,在循环很大情况下,xrange的高效率和快速将表现的很明显。我们可以用timeit 来测试一下range和xrange的执行时间。
- >>> timeit.timeit('for i in range(10000000): pass',number=1)
- >>> timeit.timeit('for i in xrange(10000000): pass',number=1)
- 0.2595210075378418
在大量循环的条件下,可以看到xrange的高效率是很明显的。
总结一下: 1、range()返回整个list。 2、xrange()返回的是一个xrange object,且这个对象是个iterable。 3、两者都用与for循环。 4、xrange()占用更少的内存空间,因为循环时xrange()只生成当前的元素,不像range()一开始就成生成完整的list。 这就是在Python 2里range和xrange的相同点和区别。
那么在Python 3里,我们在前面提到了range()被移除了,xrange()被重新命名成了range()。它们之间有区别吗? 请看下面的代码 Python 2的xrange()
- Python 2.7.6 (default, Dec 5 2013, 23:54:52)
- [GCC 4.6.3] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> x = xrange(5)
- >>> x
- xrange(5)
- >>> x[:]
- Traceback (most recent call last):
- File "", line 1, in <module>
- TypeError: sequence index must be integer, not 'slice'
- >>> x[-1]
- 4
- >>> list(x)
- [0, 1, 2, 3, 4]
- >>> dir(x)
- ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__len__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
- >>>
Python 3的range()
- Python 3.3.4 (default, Feb 23 2014, 23:07:23)
- [GCC 4.6.3] on linux
- Type "help", "copyright", "credits" or "license" for more information.
- >>> x = range(5)
- >>> x
- range(0, 5)
- >>> x[:]
- range(0, 5)
- >>> x[:3]
- range(0, 3)
- >>> list(x)
- [0, 1, 2, 3, 4]
- >>> x[-1]
- 4
- >>> dir(x)
- ['__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index', 'start', 'step', 'stop']
- >>>
很明显,range object在Python里增加了新的attributes,'count', 'index', 'start', 'step', 'stop', 且能支持slicing。Python 3的range()在xrange()的基础上变得更强大了。
请理解下面这句话: The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the start, stop and step values, calculating individual items and subranges as needed).
到这里,我们应该比较清楚range和xrange的区别了。
by Harrison Feng in Python
【Python那些事儿之十】range()和xrange()的更多相关文章
- python(47):range和xrange的区别和联系
range([start,] stop[, step]),根据start与stop指定的范围以及step设定的步长,生成一个序列. 比如: >>> range(5)[0, 1, 2, ...
- Python从题目中学习:range()和xrange()
近期给公司培训Python,好好啃了啃书本,查了查资料,总结一些知识点. --------------------------------------------------------------- ...
- [Python]range与xrange用法对比
[整理内容]具体如下: 先来看如下示例:>>>x=xrange(0,8)>>> print xxrange(8)>>>print x[0]0> ...
- Python中的range和xrange区别
range 函数说明:range([start,] stop[, step]),根据start与stop指定的范围以及step设定的步长,生成一个序列. range示例: >>> r ...
- python 基础 2.7 range与xrange的区别
#/usr/bin/python #coding=utf-8 #@Time :2017/10/25 19:22 #@Auther :liuzhenchuan #@File :range与xrange的 ...
- python基础-2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
1.编码转换 unicode 可以编译成 UTF-U GBK 即 #!/usr/bin/env python # -*- coding:utf-8 -*- a = '测试字符' #默认是utf-8 a ...
- python 中range与xrange的区别
先来看看range与xrange的用法介绍 help(range)Help on built-in function range in module __builtin__: range(...) r ...
- python中的range与xrange
range 也是一种类型(type),它是一个数字的序列(s sequence of numbers),而且是不可变的,通常用在for循环中. class range(stop) class rang ...
- python中range、xrange和randrange的区别
range 函数说明:range([start,] stop[, step]),根据start与stop指定的范围以及step设定的步长,生成一个列表. xrange 函数说明:和range 的用法完 ...
随机推荐
- 墨菲定律(Murphy's Law)
https://baike.baidu.com/item/墨菲定律/746284?fr=aladdin 墨菲定律是一种心理学效应,是由 爱德华·墨菲(Edward A. Murphy)提出的. 主要内 ...
- 第20章—跨域访问(CORS)
spring boot 系列学习记录:http://www.cnblogs.com/jinxiaohang/p/8111057.html 码云源码地址:https://gitee.com/jinxia ...
- String trim 坑 对于ascii码为160的去不掉
大家在使用string 的trim去除空格的时候,要注意一个坑呀,对于ascii码为160的去不掉 import java.util.Arrays; /** * Created by bjchen ...
- django博客项目3:创建 Django 博客的数据库模型
设计博客的数据库表结构 博客最主要的功能就是展示我们写的文章,它需要从某个地方获取博客文章数据才能把文章展示出来,通常来说这个地方就是数据库.我们把写好的文章永久地保存在数据库里,当用户访问我们的博客 ...
- 001-ant design pro安装、目录结构、项目加载启动【原始、以及idea开发】
一.概述 1.1.脚手架概念 编程领域中的“脚手架(Scaffolding)”指的是能够快速搭建项目“骨架”的一类工具.例如大多数的React项目都有src,public,webpack配置文件等等, ...
- Deeplearning——动态图 vs. 静态图
动态图 vs. 静态图 在 fast.ai,我们在选择框架时优先考虑程序员编程的便捷性(能更方便地进行调试和更直观地设计),而不是框架所能带来的模型加速能力.这也正是我们选择 PyTorch 的理由, ...
- python学习之路-第四天-模块
模块 sys模块 sys.argv:参数列表,'using_sys.py'是sys.argv[0].'we'是sys.argv[1].'are'是sys.argv[2]以及'arguments'是sy ...
- Oracle DG强制激活 备库
在实际运营环境中,我们经常碰到类似这样的需求,譬如想不影响现网业务评估DB补丁在现网环境中运行的时间,或者是想在做DB切换前想连接Standby DB做实际业务运行的测试,如果在9i版本的时候,想做到 ...
- mysql监控报警工具
#!/usr/bin/env python # coding:utf-8 import MySQLdb import requests, json import time url = "ht ...
- 初识JS 基本语法.基本运算符
JavaScript概述 JavaScript的历史 1992年Nombas开发出C-minus-minus(C--)的嵌入式脚本语言(最初绑定在CEnvi软件中).后将其改名ScriptEase.( ...