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

上网搜索,可以得到以下的结论:

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

  1. python 2| python 3
  2. ------------------------
  3. xrange(10)| range(10)
  4. range(10)| list(range(10))

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

  1. import sys
  2. if sys.version_info <(3,):
  3. range = xrange

所以,如非必要,否则不要 大量使用xrange, 否则以后在3.X版本(肯定是要取代2.x版本)种,你就需要修改你的习惯了和你曾经编写过的代码了,习惯一旦养成,改往往是非常痛苦的!

转载于:https://www.cnblogs.com/timest/archive/2012/08/31/2665849.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值