zoukankan      html  css  js  c++  java
  • python_xrange和range的异同

    1,range:

    函数说明:range([start,]stop[,step]),根据start和stop的范围以及步长step生成一个序列

    代码示例:

    >>> range(5)
    [0, 1, 2, 3, 4]
    >>> range(2,5)
    [2, 3, 4]
    >>> range(2,5,2)
    [2, 4]

    2,xrange

    函数说明:功能和range一样,所不同的是生成的不是一个数组而是一个生成器

    代码示例:

    >>> xrange(5)
    xrange(5)
    >>> list(xrange(5))
    [0, 1, 2, 3, 4]
    >>> xrange(2,5)
    xrange(2, 5)
    >>> list(xrange(2,5))
    [2, 3, 4]
    >>> xrange(2,5,2)
    xrange(2, 6, 2)  #注意和range(2,5,2)的区别
    >>> list(xrange(2,5,2))
    [2, 4]

    3,主要区别: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.”

    代码示例:

    >>> a = range(0,10)
    >>> print type(a)
    <type 'list'>
    >>> print a[1],a[2]
    1 2
    >>> a2 = xrange(0,10)
    >>> print type(a2)
    <type 'xrange'>
    >>> print a2[1],a2[2]
    1 2

    所以,在Range的方法中,它会生成一个list的对象,但是在XRange中,它生成的却是一个xrange的对象。当返回的东西不是很大的时候,或者在一个循环里,基本上都是从头查到底的情况下,这两个方法的效率差不多。但是,当返回的东西很大,或者循环中常常会被Break出来的话,还是建议使用XRange,这样既省空间,又会提高效率。

     

    每天多一点提高,给自己一些激励,开心生活,用编码来丰富我的生活,加油! ↖(^ω^)↗
  • 相关阅读:
    special word count
    Regular Expression
    position 之 fixed vs sticky
    查看linux并发连接数的方法
    Linux/Unix环境下的make命令详解(转)
    Redis数据结构(转)
    maven中依懒scope说明
    mysql主从复制
    linux查看是否已经安装某个软件
    在mac下使用py2app打包python项目
  • 原文地址:https://www.cnblogs.com/graceting/p/3620314.html
Copyright © 2011-2022 走看看