Python reversed反轉(zhuǎn)序列并生成可迭代對象
英文文檔:
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)序列生成新的可迭代對象
說明:
1. 函數(shù)功能是反轉(zhuǎn)一個序列對象,將其元素從后向前顛倒構(gòu)建成一個新的迭代器。
>>> a = reversed(range(10)) # 傳入range對象 >>> 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) # 傳入列表對象 <list_reverseiterator object at 0x031874D0> >>> b = reversed(a) >>> b # 類型變成迭代器 <list_reverseiterator object at 0x037C4EB0> >>> list(b) ['d', 'c', 'b', 'a']
2. 如果參數(shù)不是一個序列對象,則其必須定義一個__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) # 實例不能反轉(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) # 實例變得可以反轉(zhuǎn) >>> a.scores # 反轉(zhuǎn)后類型變成迭代器 <list_reverseiterator object at 0x0342F3B0> >>> type(a.scores) <class 'list_reverseiterator'> >>> list(a.scores) [96, 93, 85, 78]
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python實現(xiàn)SICP賦值和局部狀態(tài)
這篇文章主要介紹了Python實現(xiàn)SICP 賦值和局部狀態(tài)的相關(guān)知識,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03Python提高運行速度工具之Pandarallel的使用教程
為了提高運行速度,我們一般會采用多進程的方式。而常見的方案對于普通python玩家來說都不是特別友好,怎樣才能算作一個友好的并行處理方案?本文就來和大家講講pandarallel的使用2022-09-09python通過shutil實現(xiàn)快速文件復(fù)制的方法
這篇文章主要介紹了python通過shutil實現(xiàn)快速文件復(fù)制的方法,涉及Python中shutil模塊的使用技巧,需要的朋友可以參考下2015-03-03django商品分類及商品數(shù)據(jù)建模實例詳解
這篇文章主要介紹了django商品分類及商品數(shù)據(jù)建模實例代碼內(nèi)容,需要的朋友們學(xué)習(xí)參考下。2020-01-01pycharm打包python項目為exe執(zhí)行文件的實例代碼
這篇文章主要介紹了pycharm打包python項目為exe執(zhí)行文件,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07