zoukankan      html  css  js  c++  java
  • python range 和 xrange 区别

    引自 python官方文档 http://docs.python.org/2/library/functions.html

      range(stop)
      range(startstop[step])

    This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largeststart + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stopstep must not be zero (or else ValueError is raised). Example:

    >>> range(10)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> range(1, 11)
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> range(0, 30, 5)
    [0, 5, 10, 15, 20, 25]
    >>> range(0, 10, 3)
    [0, 3, 6, 9]
    >>> range(0, -10, -1)
    [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
    >>> range(0)
    []
    >>> range(1, 0)
    []
    xrange(stop)
    xrange(startstop[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() overrange() 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 withbreak). For more information on xrange objects, see XRange Type and Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange.

    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 theitertools module: islice(count(start, step), (stop-start+step-1+2*(step<0))//step).

    官方文档中说明range返回的是一个list,而xrange返回的是一个xrange对象,并且xrange更加简洁快速,所以在程序当中应当尽量使用xrange。
  • 相关阅读:
    SpringBoot 拦截器
    SpringBoot学习笔记1
    mysql学习1
    mybatis运行原理学习
    js学习2
    设计原则
    mybatis学习1
    spring mvc
    Jenkins流水线部署maven不同模块服务到不同服务器运行
    L2Dwidget让自己的vue项目骚起来
  • 原文地址:https://www.cnblogs.com/jeesezhang/p/3542865.html
Copyright © 2011-2022 走看看