萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python itertools 模組完整教學:高效迭代器工具箱詳解

itertools 是 Python 標準庫中提供高效迭代運算的核心模組,適用於大數據串流處理、組合生成、序列過濾等場景。本文系統整理其分類功能、參數說明與實戰範例,助你掌握「懶惰運算」的精髓。

模組架構總覽

itertools 函數可分為三大類:

  • 無限迭代器:產生無窮序列
  • 有限序列處理迭代器:消費輸入序列並產出新序列
  • 組合生成器:排列組合、笛卡兒積等

一、無限迭代器

函數參數產出結果範例
count()start=0, step=1start, 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

count() 實作原理

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 限制,可處理任意大整數。

repeat() 實作原理

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 布林值篩選 datacompress('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, seqfunc(*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() 進階用法

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']]

dropwhile() 執行流程示意

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

實戰技巧:flatmap 模式

結合 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))

Python 2 vs 3 差異提醒

  • Python 2 有 ifilter, imap, izip 等懶惰版本;Python 3 內建 filter, map, zip 均為迭代器,itertools 對應函數已移除或重命名(如 zip_longest 原為 izip_longest)。
  • 本文範例以 Python 3 語法為主。

總結

itertools 提供記憶體高效、速度極快的迭代運算工具,善用可大幅簡化序列處理邏輯。建議熟記核心函數分類與參數,實務上常搭配 operator、functools 使用。

copyright © 萬盛學電腦網 all rights reserved