range,xrange,arange比较

    xiaoxiao2021-03-25  27

    转载自: 

    http://blog.csdn.net/duankaifei/article/details/43866849

    python range介绍

    range多用作循环,range(0,10)返回一个list

    python xrange 介绍

    xrange也是用作循环,只是xrang(0,10)不返回list,返回xrange对象。每次调用返回其中的一个值。 返回很大的数的时候或者频繁的需要break时候,xrange性能更好。

    python arange

    arange是numpy模块中的函数,使用前需要先导入此模块,arange(3):返回array类型对象。

    doc说明:numpy.arange([start, ]stop, [step, ]dtype=None) Return evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list.

    import numpy as np np.arange(2) array([0, 1])

    range和xrange比较

    >>> print range.__doc__ range(stop) -> list of integers range(start, stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. >>> print xrange.__doc__ xrange(stop) -> xrange object xrange(start, stop[, step]) -> xrange object Like range(), but instead of returning a list, returns an object that generates the numbers in the range on demand. For looping, this is slightly faster than range() and more memory efficient.

    总结

    既然两者没有区别,而且在数值大的时候xrang更优越,以后coding时候尽量用xrange。

    转载请注明原文地址: https://ju.6miu.com/read-150269.html

    最新回复(0)