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. 解決Android studio xml界面無法預(yù)覽問題2. 什么是python的自省3. Springboot Druid 自定義加密數(shù)據(jù)庫密碼的幾種方案4. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁效果(實(shí)例代碼)5. 詳解Android studio 動(dòng)態(tài)fragment的用法6. Vuex localStorage的具體使用7. php模擬實(shí)現(xiàn)斗地主發(fā)牌8. IntelliJ IDEA安裝插件的方法步驟9. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)10. 使用Android studio查看Kotlin的字節(jié)碼教程

網(wǎng)公網(wǎng)安備