In some applications it may be necessary to arrange the list elements in reverse order,That is, the positions of all elements are reversed.
以下總結了pythonList common4inversion method:
一、列表對象的reverse()方法
語法:列表名.reverse()
該方法沒有返回值,Reverses all elements in the list in place
# reverse()方法
a = [1, 2, 3, 4, 5, 6, 7, 'abc', 'def']
a.reverse()
print('列表反轉結果:', a)
列表反轉結果:[‘def’, ‘abc’, 7, 6, 5, 4, 3, 2, 1]
二、內置reversed()函數
語法:reversed(列表名)
與reverse()方法不同,內置函數reversed()The function does not make any modifications to the original list,Instead, it returns an iterable object in reverse order.
# 內置reversed()函數
a = [1, 2, 3, 4, 5, 6, 7, 'abc', 'def']
a1 = reversed(a)
print('列表反轉結果(迭代對象):', a1)
print('列表反轉結果轉換成列表:', list(a1))
列表反轉結果(迭代對象):<list_reverseiterator object at 0x00000243EF467A20>
列表反轉結果轉換成列表:[‘def’, ‘abc’, 7, 6, 5, 4, 3, 2, 1]
三、切片
語法:列表名[x:y:z]
x:切片開始位置,默認為0
y:切片截止(但不包含)位置,默認為列表長度
z:切片的步長,默認為1;-1It means to start slicing from the last element
# Slices are reversed
a = [1, 2, 3, 4, 5, 6, 7, 'abc', 'def']
print('列表反轉結果:', a[::-1])
列表反轉結果:[‘def’, ‘abc’, 7, 6, 5, 4, 3, 2, 1]
四、使用for循環
# 使用for循環
a = [1, 2, 3, 4, 5, 6, 7, 'abc', 'def']
a1 = [a[len(a)-i-1] for i in range(len(a))]
print('列表反轉結果:', a1)
列表反轉結果:[‘def’, ‘abc’, 7, 6, 5, 4, 3, 2, 1]
The above is to achieve list inversion4種方法.