reversed()函数是返回序列seq的反向访问的迭代子。参数可以是列表,元组,字符串,不改变原对象。
1》参数是列表
>>> l=[1,2,3,4,5]
>>> ll=reversed(l)
>>> l
[1, 2, 3, 4, 5]
>>> ll
<listreverseiterator object at 0x06A9E930>
>>> for i in ll:#第一次遍历
... print i,
...
5 4 3 2 1
>>> for i in ll:第二次遍历为空,原因见本文最后
... print i
...
2》参数是列表
>>> l=[3,4,5,6]
>>> ll=reversed(l)
>>> l
[3, 4, 5, 6]
>>> ll
<listreverseiterator object at 0x06A07E10>
>>> list(ll)#第一次
[6, 5, 4, 3]
>>> list(ll)#第二次为空,原因见本文最后
[]
3》参数是元组
>>> t=(4,5,6)
>>> tt=reversed(t)
>>> t
(4, 5, 6)
>>> tt
<reversed object at 0x06A07E50>
>>> tuple(tt)#第一次
(6, 5, 4)
>>> tuple(tt)#第二次为空,原因见本文最后
()
4》参数是字符串
>>> s='cba'
>>> ss=reversed(s)
>>> s
'cba'
>>> ss
<reversed object at 0x06A07E70>
>>> list(ss)#第一次
['a', 'b', 'c']
>>> list(ss)#第二次为空,原因见本文最后
[]
5》参数是字符串
>>> s='1234'
>>> ss=reversed(s)
>>> s
'1234'
>>> ss
<reversed object at 0x06A94490>
>>> ''.join(ss)#第一次
'4321'
>>> ''.join(ss)#第二次为空,原因见本文最后
''
为什么reversed()之后,第二次for循环或第二次list()或第二次tuple()或第二次join()得到的结果为空?我们以第2个例子具体说明一下:
That’s because reversed creates an iterator, which is already spent when you’re calling list(ll) for the second time.
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.
总结:reversed()之后,只在第一次遍历时返回值。