欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python內(nèi)置函數(shù)reversed()用法分析

 更新時(shí)間:2018年03月20日 09:38:30   作者:快遞小可  
這篇文章主要介紹了Python內(nèi)置函數(shù)reversed()用法,結(jié)合實(shí)例形式分析了reversed()函數(shù)的功能及針對(duì)序列元素相關(guān)操作技巧與使用注意事項(xiàng),需要的朋友可以參考下

本文實(shí)例講述了Python內(nèi)置函數(shù)reversed()用法。分享給大家供大家參考,具體如下:

reversed()函數(shù)是返回序列seq的反向訪問的迭代器。參數(shù)可以是列表,元組,字符串,不改變?cè)瓕?duì)象。

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個(gè)例子具體說明一下:

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.

小編來翻譯一下:

這是因?yàn)榉聪騽?chuàng)建了一個(gè)迭代器,該迭代器在第二次調(diào)用列表(LL)時(shí)已經(jīng)使用過了。

其原因就是ll不是反轉(zhuǎn)列表本身,而是一個(gè)列表反向迭代器。所以當(dāng)你第一次調(diào)用列表(ll),它會(huì)遍歷ll并且創(chuàng)建一個(gè)新的列表從項(xiàng)目輸出迭代器。當(dāng)你再進(jìn)行一次,ll仍然是原來的迭代器,已經(jīng)經(jīng)歷了所有的項(xiàng)目,所以它不會(huì)再遍歷什么,這就造成了空列表。

總結(jié):reversed()之后,只在第一次遍歷時(shí)返回值。

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python函數(shù)使用技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論