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()之後,只在第一次遍曆時傳回值。