Python內(nèi)置函數(shù)reversed()用法分析
本文實例講述了Python內(nèi)置函數(shù)reversed()用法。分享給大家供大家參考,具體如下:
reversed()
函數(shù)是返回序列seq的反向訪問的迭代器。參數(shù)可以是列表,元組,字符串,不改變原對象。
1》參數(shù)是列表
>>> 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》參數(shù)是列表
>>> 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》參數(shù)是元組
>>> t=(4,5,6) >>> tt=reversed(t) >>> t (4, 5, 6) >>> tt <reversed object at 0x06A07E50> >>> tuple(tt)#第一次 (6, 5, 4) >>> tuple(tt)#第二次為空,原因見本文最后 ()
4》參數(shù)是字符串
>>> s='cba' >>> ss=reversed(s) >>> s 'cba' >>> ss <reversed object at 0x06A07E70> >>> list(ss)#第一次 ['a', 'b', 'c'] >>> list(ss)#第二次為空,原因見本文最后 []
5》參數(shù)是字符串
>>> s='1234' >>> ss=reversed(s) >>> s '1234' >>> ss <reversed object at 0x06A94490> >>> ''.join(ss)#第一次 '4321' >>> ''.join(ss)#第二次為空,原因見本文最后 ''
為什么reversed()
之后,第二次for循環(huán)或第二次list()
或第二次tuple()
或第二次join()
得到的結(jié)果為空?我們以第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.
小編來翻譯一下:
這是因為反向創(chuàng)建了一個迭代器,該迭代器在第二次調(diào)用列表(LL)時已經(jīng)使用過了。
其原因就是ll不是反轉(zhuǎn)列表本身,而是一個列表反向迭代器。所以當你第一次調(diào)用列表(ll),它會遍歷ll并且創(chuàng)建一個新的列表從項目輸出迭代器。當你再進行一次,ll仍然是原來的迭代器,已經(jīng)經(jīng)歷了所有的項目,所以它不會再遍歷什么,這就造成了空列表。
總結(jié):reversed()之后,只在第一次遍歷時返回值。
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python函數(shù)使用技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
對Python中小整數(shù)對象池和大整數(shù)對象池的使用詳解
今天小編就為大家分享一篇對Python中小整數(shù)對象池和大整數(shù)對象池的使用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07python的tkinter布局之簡單的聊天窗口實現(xiàn)方法
這篇文章主要介紹了python的tkinter布局之簡單的聊天窗口實現(xiàn)方法,對于tkinter用法做了初步的介紹與應(yīng)用展示,需要的朋友可以參考下2014-09-09python3.7環(huán)境下sanic-ext未生效踩坑解析
這篇文章主要為大家介紹了python3.7環(huán)境下sanic-ext未生效踩坑解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01PyTorch 遷移學(xué)習實踐(幾分鐘即可訓(xùn)練好自己的模型)
這篇文章主要介紹了PyTorch 遷移學(xué)習實踐(幾分鐘即可訓(xùn)練好自己的模型),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2021-03-03