久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

Python reversed反轉(zhuǎn)序列并生成可迭代對象

瀏覽:7日期:2022-07-07 14:20:03

英文文檔:

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í)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 万全县| 汤原县| 德兴市| 拜城县| 水城县| 澜沧| 贞丰县| 武山县| 芮城县| 文安县| 兰溪市| 瓦房店市| 信阳市| 盘山县| 雅江县| 新乡市| 扶余县| 雷州市| 泰宁县| 万源市| 修水县| 阜康市| 怀化市| 金秀| 湛江市| 安西县| 长子县| 南岸区| 犍为县| 河津市| 定远县| 贺州市| 望谟县| 天津市| 土默特左旗| 崇礼县| 成安县| 银川市| 田东县| 许昌县| 栖霞市|