python reverse()方法

2020-01-08 15:24:27 浏览数 (1)

代码语言:javascript复制
Python中  reverse()是列表的内置方法,无参数,无返回值,reverse()会改变列表(原地反转),因此无需返回值。字典、元组、字符串不具有reverse()方法,如果调用将会返回一个异常.
>>> help(list.reverse)
 Help on method_descriptor:

 reverse(...)
     L.reverse() -- reverse *IN PLACE*

>>> l=[1,2,3,4,5]
 >>> l.reverse()
 >>> l
 [5, 4, 3, 2, 1]

>>> t=(2,3,4,5,6)
 >>> t.reverse()#报错

AttributeError: 'tuple' object has no attribute 'reverse'

>>> s='python'
 >>> s.reverse()#报错

AttributeError: 'str' object has no attribute 'reverse'

>>> d={'a':1,'b':2}
 >>> d.reverse()#报错

AttributeError: 'dict' object has no attribute 'reverse'

0 人点赞