- Python進(jìn)階編程:編寫更高效、優(yōu)雅的Python代碼
- 劉宇宙 謝東 劉艷
- 407字
- 2021-04-30 12:39:48
4.1.4 反向迭代
在實(shí)際應(yīng)用中,將一個序列逆序輸出是比較常見的操作。對于迭代,這種操作稱為反方向迭代。
對于反向迭代序列,我們可以使用內(nèi)置的reversed()函數(shù),代碼(reversed_iter.py)如下:
a = [1, 2, 3, 4] print(f'primary a is: {a}') b = list() for x in reversed(a): b.append(x) print(f'{a} reversed is: {b}')
執(zhí)行py文件,輸出結(jié)果如下:
primary a is: [1, 2, 3, 4] [1, 2, 3, 4] reversed is: [4, 3, 2, 1]
反向迭代僅僅當(dāng)對象的大小可預(yù)先確定或者對象實(shí)現(xiàn)了__reversed__()函數(shù)才生效。如果兩者都不符合,必須先將對象轉(zhuǎn)換為一個列表,代碼如下:
f = open('/etc/passwd') for line in reversed(list(f)): print(line, end='')
注意 如果可迭代對象元素很多,將其預(yù)先轉(zhuǎn)換為一個列表要消耗大量的內(nèi)存。
我們可以通過在自定義類上實(shí)現(xiàn)__reversed__()方法來實(shí)現(xiàn)反向迭代,代碼(reversed_iter.py)示例如下:
class Countdown: def __init__(self, start): self.start = start # Forward iterator def __iter__(self): n = self.start while n > 0: yield n n -= 1 # Reverse iterator def __reversed__(self): n = 1 while n <= self.start: yield n n += 1 for rev_val in reversed(Countdown(20)): print(f'reversed order: {rev_val}') print() for nor_val in Countdown(20): print(f'normal order: {nor_val}')
執(zhí)行py文件,輸出結(jié)果如下:
reversed order: 1 reversed order: 2 ... reversed order: 20 normal order: 20 normal order: 19 ... normal order: 1
定義一個反向迭代器可以使代碼運(yùn)行非常高效,因?yàn)椴辉傩枰獙?shù)據(jù)填充到一個列表中,然后再去反向迭代該列表。
推薦閱讀
- Photoshop智能手機(jī)APP UI設(shè)計(jì)之道
- Bulma必知必會
- PhpStorm Cookbook
- D3.js 4.x Data Visualization(Third Edition)
- Android開發(fā)案例教程與項(xiàng)目實(shí)戰(zhàn)(在線實(shí)驗(yàn)+在線自測)
- Mastering C++ Multithreading
- Three.js權(quán)威指南:在網(wǎng)頁上創(chuàng)建3D圖形和動畫的方法與實(shí)踐(原書第4版)
- Oracle Database XE 11gR2 Jump Start Guide
- Flink核心技術(shù):源碼剖析與特性開發(fā)
- Learning jqPlot
- Mastering Swift 4(Fourth Edition)
- Microsoft Azure Security
- 微信小程序開發(fā)圖解案例教程:附精講視頻(第3版)
- Learning Android Application Development
- Java從入門到精通(微視頻精編版)