您的位置:首页 > 编程语言 > Python开发

python 的 range 和 xrange 之间那理不清的关系

2012-08-31 18:53 411 查看
上网搜索,可以得到以下的结论:

xrange(3): // 返回 xrange类型

range(3) : // 返回 list类型

之间的区别,官方doc:

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).

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

至于效率, 文档里也说了, 两者性能差不多, 除非 是个非常大的range,或则
在loop的时候用到break,这样的化,xrange性能更佳。 原因是:This is an opaque sequence type
which yields the same values as the corresponding list, without
actually storing them all simultaneously.

故事还没有结束, 那我们以后都应该用xrange吗?NO! 在3.X后的版本,两者的区别没了,因为:

In python 3,
range replaces xrange so that

python 2| python 3


------------------------


xrange(10)| range(10)


range(10)| list(range(10))


If you want a
python 3 behavior in python 2, you can write

import sys


if sys.version_info <(3,):


range = xrange


所以,如非必要,否则不要 大量使用xrange,
否则以后在3.X版本(肯定是要取代2.x版本)种,你就需要修改你的习惯了和你曾经编写过的代码了,习惯一旦养成,改往往是非常痛苦的!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: