range(start, stop[, step])
range反序输出n-m:
应使start = m ,stop = n-1,step = -1
例 输出1-5的反序
l = []
for i in range(5, 0, -1):
l.append(i)
print(l)
E:\python13\venv\Scripts\python.exe E:/python13/just_just.py
[5, 4, 3, 2, 1]
Process finished with exit code 0
错误写法:
l = []
for i in range(5, 1, 1):
l.append(i)
print(l)
l1 = []
for i in range(1, 5, -1):
l1.append(i)
print(l1)
E:\python13\venv\Scripts\python.exe E:/python13/just_just.py
[]
[]
Process finished with exit code 0
原因:
step: 步长,为负时,从右向左取值(stop-->start)此时若start < stop,输出为空,为正时,从左向右取值(start-->stop)此时若start > stop ,输出为空。
列表切片同理:
示例:
l = [1, 2, 3, 4, 5]
print(l[::-1])
print(l[1:4:-1])
print(l[1:4:1])
print(l[4:1:-1])
print(l[4:1:1])
E:\python13\venv\Scripts\python.exe E:/python13/just_just.py
[5, 4, 3, 2, 1]
[]
[2, 3, 4]
[5, 4, 3]
[]
Process finished with exit code 0