當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python List reverse()用法及代碼示例


列出 reverse() 方法

reverse() 方法用於反轉列表中的元素,該方法使用此列表(我們必須反轉元素的列表)調用,並反轉列表中的所有元素。

用法:

    list_name.reverse()

參數:

  • 它不接受任何參數。

返回值:

這個方法的返回類型是<class 'NoneType'>,它什麽都不返回。

範例1:

# Python List reverse() Method with Example

# declaring the list
cars = ["BMW", "Porsche", "Audi", "Lexus", "Audi"]

# printing the list
print("cars before reverse operations...")
print("cars:", cars)

# reversing the list elements
cars.reverse()

# printing the list 
print("cars after reverse operations...")
print("cars:", cars)

輸出

cars before reverse operations...
cars: ['BMW', 'Porsche', 'Audi', 'Lexus', 'Audi']
cars after reverse operations...
cars: ['Audi', 'Lexus', 'Audi', 'Porsche', 'BMW']

範例2:

# Python List reverse() Method with Example

# declaring the list
x = [100, 200, 30, 40, 50, 60, 700]

# printing the list
print("x before reverse operations...")
print("x:", x)

# reversing list elements
x.reverse();

# printing the list
print("x after reverse operations...")
print("x:", x)

輸出

x before reverse operations...
x: [100, 200, 30, 40, 50, 60, 700]
x after reverse operations...
x: [700, 60, 50, 40, 30, 200, 100]


相關用法


注:本文由純淨天空篩選整理自 Python List reverse() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。