《Python Cookbook 3rd》笔记(4.8):跳过可迭代对象的开始部分
跳過可迭代對象的開始部分
問題
你想遍歷一個可迭代對象,但是它開始的某些元素你并不感興趣,想跳過它們。
解法
itertools 模塊中有一些函數可以完成這個任務。首先介紹的是itertools.dropwhile() 函數。使用時,你給它傳遞一個函數對象和一個可迭代對象。它會返回一個迭代器對象,丟棄原有序列中直到函數返回 True 之前的所有元素,然后返回后面所有元素。
為了演示,假定你在讀取一個開始部分是幾行注釋的源文件。比如:
>>> with open('/etc/passwd') as f: ... for line in f: ... print(line, end='') ... ## # User Database # # Note that this file is consulted directly only when the system is running # in single-user mode. At other times, this information is provided by # Open Directory. ... ## nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false root:*:0:0:System Administrator:/var/root:/bin/sh ... >>>如果你想跳過開始部分的注釋行的話,可以這樣做:
>>> from itertools import dropwhile >>> with open('/etc/passwd') as f: ... for line in dropwhile(lambda line: line.startswith('#'), f): ... print(line, end='') ... nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false root:*:0:0:System Administrator:/var/root:/bin/sh ... >>>這個例子是基于根據某個測試函數跳過開始的元素。如果你已經明確知道了要跳過的元素的個數的話,那么可以使用 itertools.islice() 來代替。比如:
>>> from itertools import islice >>> items = ['a', 'b', 'c', 1, 4, 10, 15] >>> for x in islice(items, 3, None): ... print(x) ... 14 10 15 >>>在這個例子中, islice() 函數最后那個 None 參數指定了你要獲取從第 3 個到最后的所有元素,如果 None 和 3 的位置對調,意思就是僅僅獲取前三個元素恰恰相反,(這個跟切片的相反操作 [3:] 和 [:3] 原理是一樣的)。
討論
函數 dropwhile() 和 islice() 其實就是兩個幫助函數,為的就是避免寫出下面這種冗余代碼:
with open('/etc/passwd') as f:# Skip over initial commentswhile True:line = next(f, '')if not line.startswith('#'):break# Process remaining lineswhile line:# Replace with useful processingprint(line, end='')line = next(f, None)跳過一個可迭代對象的開始部分跟通常的過濾是不同的。比如,上述代碼的第一個部分可能會這樣重寫:
with open('/etc/passwd') as f:lines = (line for line in f if not line.startswith('#'))for line in lines:print(line, end='')這樣寫確實可以跳過開始部分的注釋行,但是同樣也會跳過文件中其他所有的注釋行。換句話講,我們的解決方案是僅僅跳過開始部分滿足測試條件的行,在那以后,所有的元素不再進行測試和過濾了。
最后需要著重強調的一點是,本節的方案適用于所有可迭代對象,包括那些事先不能確定大小的,比如生成器,文件及其類似的對象。
總結
以上是生活随笔為你收集整理的《Python Cookbook 3rd》笔记(4.8):跳过可迭代对象的开始部分的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python模块(5)-Matplotl
- 下一篇: 《Python Cookbook 3rd