How to reverse a range in Python如何在python中反转序列

Reversing a range or a sequence of numbers results in a sequence containing the numbers from the range in reverse order.

反转一个范围或一个数字序列会产生一个包含该范围中的数字的序列,顺序与此相反。

USE range() WITH A NEGATIVE STEP TO CREATE A RANGE IN REVERSE 使用带有反向的range()创建反向范围

Call range(start, stop, step) with a negative integer as step to create an immutable sequence of numbers from start up to, but not including, stop.

reversed_range = range(3, 0, -1)

Sequence of numbers with negative step 带负步长的数列

for number in reversed_range:
    print(number)
OUTPUT
3
2
1

USE reversed() TO REVERSE A RANGE使用reversed()反转序列

Call range(start, stop) to create an immutable sequence of numbers from start up to, but not including, stop. Use reversed(sequence) with sequence as the previous result to return the integers in sequence in reverse order.

a_range = range(1, 4)
reversed_range = reversed(a_range)

Reverse the sequence’s order

for number in reversed_range:
print(number)
OUTPUT
3
2
1