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()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。