当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。