Python Itertools:高效能迭代實用程式

學習Python的itertools模組。掌握無限迭代器、組合、排列、分組和記憶體高效的資料處理。

在編輯器中嘗試

概述

Python 內建的「itertools」模組是用來處理迭代器的工具集合。迭代器是一個按順序產生項目的對象,「itertools」提供了高度最佳化的 C 實作函數,可以連結、過濾、分組和組合這些迭代器。透過利用這些工具而不是編寫巢狀循環和清單副本,您可以顯著加快執行速度並減少資料管道的記憶體開銷。

itertools 模組將其工具分為三個主要群組。首先是無限迭代器,例如「count()」(無限地計數)、「cycle()」(重複循環遍歷集合)和「repeat()」。其次是組合迭代器,例如“permutations()”和“combinations()”,它們對於數學建模、最佳化和生成遊戲排列非常有用。第三種是終止迭代器,如“accumulate()”和“groupby()”。

一個特別強大的工具是“itertools.groupby()”,它將連續的鍵和值分組到一個可迭代物件中。另一個是“itertools.chain()”,它將多個可迭代物件連結在一起,以便它們可以作為單一連續列表進行處理,而無需複製元素。處理大型資料集時,使用 itertools 可確保您延遲處理元素(僅在需要時評估它們),從而保留伺服器記憶體並最大化吞吐量。

程式碼和執行輸出

使用 itertool 連結集合並產生數學組合。

itertools_demo.py
在編輯器中嘗試
import itertools

# Chaining iterables together
list_a = [1, 2]
list_b = [3, 4]
combined = list(itertools.chain(list_a, list_b))
print(f"Combined via chain: {combined}")

# Generating combinations (choose 2 items out of 3)
items = ["A", "B", "C"]
combos = list(itertools.combinations(items, 2))
print(f"Combinations (2 of 3): {combos}")

# Cycle through a list (limited to prevent infinite loop)
cycler = itertools.cycle(["Red", "Blue"])
cycle_output = [next(cycler) for _ in range(4)]
print(f"Cycle sequence: {cycle_output}")
端子輸出
Combined via chain: [1, 2, 3, 4]
Combinations (2 of 3): [('A', 'B'), ('A', 'C'), ('B', 'C')]
Cycle sequence: ['Red', 'Blue', 'Red', 'Blue']

逐步實施

  • 在演算法中產生可能的移動或密碼排列
  • 將關係資料集條目進行分組(例如按月對交易進行分組)
  • 在遊戲中創建循環隊列或輪流

常見問題解答

為什麼 itertools 可以提高效能?

因為它的函數會傳回惰性迭代(一次評估一個專案),並且是在 Python 解釋器中用快速編譯的 C 程式碼編寫的。

組合和排列有什麼差別?

組合忽略順序(('A', 'B') 與 ('B', 'A') 相同),而排列將順序視為唯一並傳回兩種排列。

相關主題

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。