易截截图软件、单文件、免安装、纯绿色、仅160KB

Python中Range和XRange的区别

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,


相关文档:

Python 序列


Python 序列
列表、元组和字符串都是序列,但是序列是什么,它们为什么如此特别呢?序列的两个主要特点是索引操作符和切片操作符。索引操作符让我们可以从序列中抓取一个特定项目。切片操作符让我们能够获取序列的一个切片,即一部分序列。
使用序列
例9.5 使用序列
#!/usr/bin/python
# Filename: seq.py
shoplist ......

Python之感

从去年还没毕业就接触Python,上周有些无聊重新再看一遍,发现其确实不错。语法简单,一个下午基本了解,使用Pydev插件在Eclipse中进行开发基本上没有任何障碍。重点是其效率很高,不需编译直接运行。比较适合进行数据的预处理。不错,以后有机会好好用用。 ......

python技巧(3)——下划线,私有变量

Python 用下划线作为变量前缀和后缀指定特殊变量。
_xxx     
不能用'from module import *'导入
__xxx__ 系统定义名字
__xxx   
类中的私有变量名
核心风格:避免用下划线作为变量名的开始。
因为下划线对解释器有特殊的意义,而且是内建标识符所使用的符号,我们建议程序 ......

Pyke 简介 (3) :调制 Python 函数

对 Python 函数的"调制",是指对其做出合乎需求的设置。具体的调制方法,是将其参数设为固定值(常数)。
设定单一的参数值
原先的函数是这样的:
>>> def foo(cooked, standard):
... print "foo called with cooked: %s, standard: %s" % \
... (cooked, standard) 
调用它:
>>> foo('a', ......

python列表和字典的方法总结

列表方法:


方法
说明
append( item )
在列表末尾插入(item )
count( element )
返回element在列表中出现的次数
extend( newlist )
将newlist的元素插入列表末尾
index( element )
返回element在列表中的索引,如果不存在,则引发ValueError异常
insert( index , item )
在index ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号