The method of reverse order of python list

a = [0,1,2,3,4,5,6,7,8,9]

b = a[i:j] means copying a[i] to a[j-1] to generate a new list object
b = a[1:3] Then, the content of b is [1,2]
when i is missing Time-saving, the default is 0, that is, a[:3] is equivalent to a[0:3]
when j is default, the default is len(alist), that is, a[1:] is equivalent to a[1:10]
when i , j is default, a[:] is equivalent to a complete copy of a

The format of b = a[i:j:s], i, j are the same as above, but s means stepping, the default is 1. So
a[i:j:1] is equivalent to a[i:j ]
When s<0, i defaults to -1. j defaults to -len(a)-1,
so a[::-1] is equivalent to a[-1:-len(a )-1:-1], that is, copy from the last element to the first element. It is equivalent to turning the list backwards.


a = [0,1,2,3,4,5,6,7,8,9]
print(-len(a))
print(-len(a)-1)
print(a[::-1])
print(a[-1:-len(a)-1:-1])
a.reverse()
print(a)

 

D:\MC\venv\Scripts\python.exe D:/MC/test03.py
-10
-11
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Process finished with exit code 0
# 方法一:reserve

# 改变原来列表

list.reverse()

print(list)

#方法二: 切片 mylist[start:end:step]

#创建副本

list2 = list[::-1]

print(list2)

# 方法三:使用reversed() 方法

list3=[]

for i in reversed(list):

list3.append(i)

print(list3)

Guess you like

Origin blog.csdn.net/weixin_42550871/article/details/124468382