免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 15980 | 回复: 2

xrange与range [复制链接]

论坛徽章:
0
发表于 2010-02-04 00:51 |显示全部楼层
Python中Range和XRange的区别(Difference between Range and XRange in Python)最近机器出了点问题,所以一直没有写新的东西出来。之前在读Python的代码的时候,发觉好多人喜欢用XRange,而不是Range,我也只是记得学习的时候开始学到的是Range,后面又看到有个XRange,当时也没有深究,为什么Python里面要有两个同样的功能的系统函数。今天再去仔细查了下文档,原来它们之间还是有点区别,虽然不是很大,但至少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.
在Range的方法中,它会生成一个list的对象,但是在XRange中,它生成的却是一个xrange的对象,当返回的东西不是很大的时候,或者在一个循环里,基本上都是从头查到底的情况下,这两个方法的效率差不多。但是,当返回的东西很大,或者循环中常常会被Break出来的话,还是建议使用XRange,这样既省空间,又会提高效率。
下面举个例子:
如果使用range函数,执行下面的语句,将会得到后面的结果:
>>> a = range(0,100)>>> print type(a)>>> print a[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]>>> print a[0], a[1]0 1 但是,将开始的range用xrange替换,将会得到不同的结果:
>>> a = xrange(0,100)>>> print type(a)>>> print axrange(100)>>> print a[0], a[1]0 1

这里可以很直接的看到它们的不同点,虽然a[0], a[1]返回的值是相同的。所以,以后coding的时候还是尽可能使用xrange了
               
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/93014/showart_2177334.html

论坛徽章:
0
发表于 2011-06-10 16:50 |显示全部楼层
支持。。

论坛徽章:
0
发表于 2011-11-02 23:07 |显示全部楼层
python3中没有range了,xrange改名为range了
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP