当我们在循环中用到for或者while针对一段数字进行循环的时候,我们其实是可以直接表达其范围的,但是为啥python还是要引入range函数呢?
作为python的内置函数,个人推测range是在其他内置函数中需要用到list的index时候需要的,所以可以看到range函数的定义:
Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, …, j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When a step is given, it specifies the increment (or decrement).
包含开始数字,而将停止的数字排除在外,比如range(5):
有意思的是,这是python3的range函数,而python2的xrange函数反而是更加高速和占用较小内存的。
可以利用python的内嵌函数timeit 与 sys.getsizeof 进行测试:
python -m timeit 'for i in range(1000000):' ' pass'
10 loops, best of 3: 90.5 msec per loop
# testing xrange()
python -m timeit 'for i in xrange(1000000):' ' pass'
10 loops, best of 3: 51.1 msec per loop
--------------------------------------------
xr = xrange(1, 10000)
r = range(1, 10000)
size_xr = sys.getsizeof(xr)
size_r = sys.getsizeof(r)
print(f"The xrange() function uses {size_xr} bytes of memory.")
print(f"The range() function uses {size_r} bytes of memory.")
输出是:
The xrange() function uses 24 bytes of memory.
The xrange() function uses 80064 of memory.