Python itertools 模組實用教學 | Python
Python 的 itertools 模組提供了一系列高效的迭代器工具,讓你在處理迴圈與組合運算時更加簡潔有力。無論是無限序列、排列組合,還是多個可迭代物件的串接,itertools 都能幫你輕鬆完成。
什麼是 itertools?
itertools 是 Python 標準函式庫中專門處理迭代操作的模組。它提供的函式都回傳迭代器(Iterator),不會一次產生所有結果,因此在處理大量資料時非常節省記憶體。使用前需要先匯入:
import itertools
無限迭代器:count、cycle、repeat
itertools 提供三個能產生無限序列的迭代器,使用時務必搭配中斷條件,避免無窮迴圈。
from itertools import count, cycle, repeat
# count(start, step) — 從 start 開始,每次加 step
for num in count(10, 3):
if num > 20:
break
print(num, end=" ")
# 輸出:10 13 16 19
# cycle(iterable) — 無限循環可迭代物件
counter = 0
for item in cycle(["A", "B", "C"]):
if counter >= 6:
break
print(item, end=" ")
counter += 1
# 輸出:A B C A B C
# repeat(value, times) — 重複產生指定值
list(repeat("Hello", 3))
# 輸出:['Hello', 'Hello', 'Hello']
用 chain() 串接多個可迭代物件
chain() 可以將多個可迭代物件串成一個連續的迭代器,就像把多條鏈子接在一起:
from itertools import chain
list1 = [1, 2, 3]
list2 = ["a", "b"]
list3 = [True, False]
result = list(chain(list1, list2, list3))
print(result)
# 輸出:[1, 2, 3, 'a', 'b', True, False]
用 islice() 切片迭代器
一般的切片語法(如 [1:5])無法用在迭代器上,islice() 可以解決這個問題:
from itertools import islice, count
# 從無限計數器中取出第 5 到第 9 個元素
result = list(islice(count(0), 5, 10))
print(result)
# 輸出:[5, 6, 7, 8, 9]
# 取前 5 個元素
result = list(islice(range(100), 5))
print(result)
# 輸出:[0, 1, 2, 3, 4]
排列組合工具
itertools 提供了三個處理排列組合的函式,在數學運算與資料分析中非常實用。
from itertools import product, permutations, combinations
# product() — 笛卡爾積(Cartesian Product)
result = list(product("AB", "12"))
print(result)
# 輸出:[('A', '1'), ('A', '2'), ('B', '1'), ('B', '2')]
# permutations() — 排列(順序有差)
result = list(permutations("ABC", 2))
print(result)
# 輸出:[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
# combinations() — 組合(順序無差)
result = list(combinations("ABC", 2))
print(result)
# 輸出:[('A', 'B'), ('A', 'C'), ('B', 'C')]
permutations() 在意順序,所以 ('A', 'B') 與 ('B', 'A') 是不同結果;combinations() 不在意順序,所以只會出現一次。
用 groupby() 分組資料
groupby() 可以將連續相同鍵值的元素分為一組。使用前需要先排序,否則相同的鍵值若不連續,會被分成多組:
from itertools import groupby
# 按成績等級分組
students = [
("小明", "A"), ("小華", "B"), ("小美", "A"),
("小強", "B"), ("小芳", "A")
]
# 先依等級排序
students.sort(key=lambda x: x[1])
for grade, group in groupby(students, key=lambda x: x[1]):
names = [name for name, _ in group]
print(f"{grade}: {names}")
# 輸出:
# A: ['小明', '小美', '小芳']
# B: ['小華', '小強']
實用範例:產生密碼組合
結合 itertools 的多個函式,可以輕鬆產生各種組合:
from itertools import product
# 產生所有 4 位數字密碼(示範前 5 組)
from itertools import islice
digits = "0123456789"
passwords = product(digits, repeat=4)
first_five = list(islice(passwords, 5))
for p in first_five:
print("".join(p))
# 輸出:
# 0000
# 0001
# 0002
# 0003
# 0004
總結
itertools 模組是 Python 中處理迭代操作的強大工具箱。本文介紹了無限迭代器(count、cycle、repeat)、串接工具(chain)、切片工具(islice)、排列組合(product、permutations、combinations)以及分組工具(groupby)。善用這些工具,可以讓你的程式碼更簡潔、更有效率。希望這篇文章能幫助你在日常開發中活用 itertools 模組。
如果你想進一步了解迭代器的基本概念,請參考 Python 迭代器教學。
關於生成器的用法與應用,請閱讀 Python 生成器教學。