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


Python list reverse()用法及代码示例


reverse()是Python编程语言中的一种内置方法,可就地反转列表对象。

用法:

list_name.reverse()

参数:


There are no parameters

返回值:

The reverse() method does not return any value but 
reverse the given object from the list.

代码#1:

# Python3 program to demonstrate the  
# use of reverse method  
   
# a list of numbers 
list1 = [1, 2, 3, 4, 1, 2, 6]  
list1.reverse()  
print(list1)  
  
# a list of characters 
list2 = ['a', 'b', 'c', 'd', 'a', 'a']  
list2.reverse()  
print(list2) 

输出:

[6, 2, 1, 4, 3, 2, 1]
['a', 'a', 'd', 'c', 'b', 'a']

错误:

When anything other than list is used in place of list, 
then it returns an AttributeError

代码#2:

# Python3 program to demonstrate the  
# error in reverse() method 
   
# error when string is used in place of list 
string = "abgedge" 
string.reverse()  
print(string)

输出:

Traceback (most recent call last):
  File "/home/b3cf360e62d8812babb5549c3a4d3d30.py", line 5, in 
    string.reverse() 
AttributeError:'str' object has no attribute 'reverse' 

实际应用:
给定一个数字列表,请检查该列表是否为回文。
注意:palindrome-sequence向后读取相同的内容

代码#3:

# Python3 program for the  
# practical application of reverse()  
  
list1 = [1, 2, 3, 2, 1] 
  
# store a copy of list 
list2 = list1.copy()   
  
# reverse the list 
list2.reverse()  
  
# compare reversed and original list  
if list1 == list2:
    print("Palindrome")  
else:
    print("Not Palindrome") 

输出:

Palindrome



注:本文由纯净天空筛选整理自Striver大神的英文原创作品 Python list | reverse()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。