itertools 是 Python 標準庫中提供高效迭代運算的核心模組,適用於大數據串流處理、組合生成、序列過濾等場景。本文系統整理其分類功能、參數說明與實戰範例,助你掌握「懶惰運算」的精髓。
itertools 函數可分為三大類:
| 函數 | 參數 | 產出結果 | 範例 |
|---|---|---|---|
count() | start=0, step=1 | start, start+step, start+2*step ... | count(10) → 10, 11, 12... |
cycle() | iterable | 循環重複元素 | cycle('ABCD') → A B C D A B C D... |
repeat() | elem, [times] | 重複 elem,times 次或無限 | repeat(10, 3) → 10, 10, 10 |
def count(start=0, step=1):
n = start
while True:
yield n
n += step
等價於 (start + step * i for i in count())。注意:Python 3 無 sys.maxint 限制,可處理任意大整數。
def repeat(object, times=None):
if times is None:
while True:
yield object
else:
for _ in range(times):
yield object
| 函數 | 參數 | 行為說明 | 範例 |
|---|---|---|---|
chain() | *iterables | 串聯多個可迭代物件 | chain('ABC', 'DEF') → A B C D E F |
compress() | data, selectors | 依 selectors 布林值篩選 data | compress('ABCDEF', [1,0,1,0,1,1]) → A C E F |
dropwhile() | pred, seq | 丟棄 pred 為 True 的前綴,之後全保留 | dropwhile(lambda x: x<5, [1,4,6,4,1]) → 6 4 1 |
takewhile() | pred, seq | 保留 pred 為 True 的前綴,之後全丟棄 | takewhile(lambda x: x<5, [1,4,6,4,1]) → 1 4 |
groupby() | iterable, key=None | 依 key 函數分組,返回 (key, group) 迭代器 | 見下文詳細範例 |
islice() | seq, [start,] stop [, step] | 切片操作,支援無限序列 | islice('ABCDEFG', 2, None) → C D E F G |
starmap() | func, seq | func(*seq[i]),解包參數呼叫 | starmap(pow, [(2,5),(3,2)]) → 32, 9 |
tee() | it, n | 將一個迭代器複製為 n 個獨立迭代器 | 適用於多次遍歷同一資料源 |
zip_longest() | *iterables, fillvalue=None | 長度不一時以 fillvalue 補齊 | zip_longest('ABCD', 'xy', fillvalue='-') → Ax By C- D- |
groupby 依據 key 函數將連續相同鍵值的元素分組,輸入必須預先排序 才能獲得完整分群:
from itertools import groupby
data = ['A','A','A','B','B','C','C','D','A','A','B']
# 未排序:分群為 A, B, C, D, A, B
print([k for k,_ in groupby(data)]) # ['A','B','C','D','A','B']
# 排序後:分群為 A, B, C, D
sorted_data = sorted(data)
print([k for k,_ in groupby(sorted_data)]) # ['A','B','C','D']
print([list(g) for _,g in groupby(sorted_data)]) # [['A','A','A','A','A'], ['B','B','B'], ['C','C'], ['D']]
def dropwhile(predicate, iterable):
it = iter(iterable)
for x in it:
if not predicate(x):
yield x
break
for x in it:
yield x
| 函數 | 參數 | 說明 | 範例 (輸入 'ABCD') |
|---|---|---|---|
product() | p, q, ..., repeat=1 | 笛卡兒積(可重複) | product('AB', repeat=2) → AA AB BA BB |
permutations() | p, r=None | 全排列(不重複元素,順序敏感) | permutations('AB', 2) → AB BA |
combinations() | p, r | 組合(不重複,順序不敏感) | combinations('AB', 2) → AB |
combinations_with_replacement() | p, r | 組合(可重複元素) | combinations_with_replacement('AB', 2) → AA AB BB |
結合 chain.from_iterable 與 map 實現扁平化映射:
from itertools import chain
def flatmap(func, items):
return chain.from_iterable(map(func, items))
# 列出多個目錄下所有檔案
import os
dirs = ['/path/a', '/path/b']
all_files = list(flatmap(os.listdir, dirs))
ifilter, imap, izip 等懶惰版本;Python 3 內建 filter, map, zip 均為迭代器,itertools 對應函數已移除或重命名(如 zip_longest 原為 izip_longest)。itertools 提供記憶體高效、速度極快的迭代運算工具,善用可大幅簡化序列處理邏輯。建議熟記核心函數分類與參數,實務上常搭配 operator、functools 使用。