python内置函数之range()
先看官方解释
"""
range(stop) -> range object
range(start, stop[, step]) -> range object
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 step is given, it specifies the increment (or decrement).
"""
它的功能是返回一个整数序列,有三个参数start、stop、step,分别指定序列的起点、终点和步长:
- 指定一个参数,默认是终点,返回:0,1,2,stop-1
- 同时指定起点(包括)和终点(排除),默认每次递增1,即step默认为1
- 同时指定三个参数分别是起点、终点和步长,步长可以是负数,表示递减
注意:
-
一般配合for循环使用,遍历取值
-
python2返回的结果存放在列表中,python3返回range对象,支持循环取值
用法举例1
for i in range(10):
print(i, end=',')
# output: 0,1,2,3,4,5,6,7,8,9,
用法举例2
for i in range(2, 10, 2):
print(i, end=',')
# output: 2,4,6,8,
用法举例3
for i in range(10, 1, -1):
print(i, end=',')
# output: 10,9,8,7,6,5,4,3,2,