Python reversed反轉(zhuǎn)序列并生成可迭代對(duì)象
英文文檔:
reversed(seq)
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).
反轉(zhuǎn)序列生成新的可迭代對(duì)象
說明:
1. 函數(shù)功能是反轉(zhuǎn)一個(gè)序列對(duì)象,將其元素從后向前顛倒構(gòu)建成一個(gè)新的迭代器。
>>> a = reversed(range(10)) # 傳入range對(duì)象>>> a # 類型變成迭代器<range_iterator object at 0x035634E8>>>> list(a)[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]>>> a = [’a’,’b’,’c’,’d’]>>> a[’a’, ’b’, ’c’, ’d’]>>> reversed(a) # 傳入列表對(duì)象<list_reverseiterator object at 0x031874D0>>>> b = reversed(a)>>> b # 類型變成迭代器<list_reverseiterator object at 0x037C4EB0>>>> list(b)[’d’, ’c’, ’b’, ’a’]
2. 如果參數(shù)不是一個(gè)序列對(duì)象,則其必須定義一個(gè)__reversed__方法。
# 類型Student沒有定義__reversed__方法>>> class Student: def __init__(self,name,*args): self.name = name self.scores = [] for value in args: self.scores.append(value) >>> a = Student(’Bob’,78,85,93,96)>>> reversed(a) # 實(shí)例不能反轉(zhuǎn)Traceback (most recent call last): File '<pyshell#37>', line 1, in <module> reversed(a)TypeError: argument to reversed() must be a sequence>>> type(a.scores) # 列表類型<class ’list’># 重新定義類型,并為其定義__reversed__方法>>> class Student: def __init__(self,name,*args): self.name = name self.scores = [] for value in args: 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)<class ’list’>>>> reversed(a) # 實(shí)例變得可以反轉(zhuǎn)>>> a.scores # 反轉(zhuǎn)后類型變成迭代器<list_reverseiterator object at 0x0342F3B0>>>> type(a.scores)<class ’list_reverseiterator’>>>> list(a.scores)[96, 93, 85, 78]
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明2. PHP設(shè)計(jì)模式中工廠模式深入詳解3. CSS hack用法案例詳解4. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過程(親測(cè)可用)5. 用css截取字符的幾種方法詳解(css排版隱藏溢出文本)6. asp中response.write("中文")或者js中文亂碼問題7. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析8. PHP session反序列化漏洞超詳細(xì)講解9. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向10. ASP+ajax實(shí)現(xiàn)頂一下、踩一下同支持與反對(duì)的實(shí)現(xiàn)代碼
