Python列表反向()

Python List reverse()是Python编程语言中的一个内置方法,用于反转 列表 在正确的位置

null

语法:

列出你的名字。反向

参数:

没有参数。

返回:

reverse()方法不返回任何值,而是从列表中反转给定对象。

错误:

当使用列表以外的任何内容代替列表时,它将返回AttributeError

例1:颠倒列表

Python3

# 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']

例2: 证明 这个 错误 在reverse()方法中

Python3

# 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' 

例3:实际应用

给出一个数字列表,检查列表是否为 回文的 .

注: 回文序列,前后读相同。

Python3

# 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
© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享