List.reverse()
Python中 reverse()是列表的内置方法,无参数,无返回值.
reverse()会改变列表(原地反转),因此无需返回值。
字典 (dict),元组 (tuple),字符串 (str)不具有 reverse()方法,如果调用将会返回一个异常.
>>>help(list.reverse)
Helpon method_descriptor:
reverse(...)
L.reverse()--reverse*IN PLACE*
例如:
>>>i=[1,2,3,4,5]
>>>i.reverse()
>>>i
[5,4,3,2,1]
>>>t=(2,3,4,5,6)
>>>t.reverse()
Traceback(most recent call last):
File"",line1,in
t.reverse()
AttributeError:'tuple'object has no attribute'reverse'
>>>s='python'
>>>s.reverse()
Traceback(most recent call last):
File"",line1,in
s.reverse()
AttributeError:'str'object has no attribute'reverse'
>>>d={'a':1,'b':2}
>>>d.reverse()
Traceback(most recent call last):
File"",line1,in
d.reverse()
AttributeError:'dict'object has no attribute'reverse'
2.reversed(seq)
参数可以是列表,元组,字符串,不改变原对象。
函数功能是 反转一个序列对象,将其元素从后向前颠倒构建成一个新的迭代器 (迭代器的意思是 只能通过循环来输出)。
>>>a=reversed(range(10))# 传入range对象
>>>a# 类型变成迭代器
>>>list(a)
[9,8,7,6,5,4,3,2,1,0]
>>>a=['a','b','c','d']
>>>a
['a','b','c','d']
>>>reversed(a)# 传入列表对象
>>>b=reversed(a)
>>>b# 类型变成迭代器
>>>list(b)
['d','c','b','a']
如果参数不是一个序列对象,则其必须定义一个 __reversed__方法。
# 类型Student没有定义__reversed__方法
>>>classStudent:
def__init__(self,name,*args):
self.name=name
self.scores=[]
forvalueinargs:
self.scores.append(value)
>>>a=Student('Bob',78,85,93,96)
>>>reversed(a)# 实例不能反转
Traceback(most recent call last):
File"",line1,in
reversed(a)
TypeError:argument to reversed()must be a sequence
>>>type(a.scores)# 列表类型
# 重新定义类型,并为其定义__reversed__方法
>>>classStudent:
def__init__(self,name,*args):
self.name=name
self.scores=[]
forvalueinargs:
self.scores.append(value)
def__reversed__(self):
self.scores=reversed(self.scores)
>>>a=Student('Bob',78,85,93,96)
>>>a.scores# 列表类型
[78,85,93,96]
>>>type(a.scores)
>>>reversed(a)# 实例变得可以反转
>>>a.scores# 反转后类型变成迭代器
>>>type(a.scores)
>>>list(a.scores)
[96,93,85,78]
可以不用看了
2.1 官方文档
序列必须具有reversed()方法或支持序列协议对象( __len__()方法和 __getitem__()方法整数参数都是从0开始 )。
Return a reverse iterator. seq must be an object which has a __reversed__()method or supports the sequence protocol (the __len__() method and the __getitem__()method with integer arguments starting at 0).
2.2 示例
>>>i=[1,2,3,4,5]
>>>ii=reversed(i)
>>>ii
>>>foraini:
print(a,end=' ')
12345
>>>forainii:
print(a,end=' ')
54321
# 第二次遍历为空
>>>forainii:
print(a,end=' ')
>>>
其他类型如 tuple, str方法都和上面一样。
问题
为什么 reversed()之后,第二次 for循环或第二次 list()或第二次 tuple()或第二次 join()得到的结果为空?
答案:
原因是,ll不是反转列表本身,而是一个listreverseiterator。所以当你第一次调用列表LL时,会创建一个新的列表从项目输出迭代器。当你做第二次时,ll仍然是原来的迭代器,已经经历了所有的项目,所以它不重复什么,造成空列表。
The reason is that ll is not the reversed list itself, but a listreverseiterator. So when you call list(ll) the first time, it iterates over ll and creates a new list from the items output from that iterator.When you do it a second time, ll is still the original iterator and has already gone through all the items, so it doesn’t iterate over anything, resulting in an empty list.