在 Python 中,map、filter、reduce 是三個非常經典的函數式工具,
能用「描述做什麼」取代「一步一步怎麼做」,讓程式更簡潔、可讀。
本篇會用白話說明 + 實際範例,一步一步帶你理解。
✅ 一、先建立一份測試資料
numbers = [1, 2, 3, 4, 5, 6]✅ 二、map:對每個元素「各自做一次」
📌 概念
map會把 一元函數 套用到「每一個元素」
📐 形式
map(function, iterable)✅ 範例 1:全部乘以 2
result = map(lambda x: x * 2, numbers)
list(result)輸出:
👉 等同於:
[x * 2 for x in numbers]✅ 範例 2:數字轉字串
result = map(str, numbers)
list(result)✅ 三、filter:留下「符合條件」的元素
📌 概念
filter使用 回傳 True / False 的一元函數
📐 形式
filter(function, iterable)✅ 範例 1:只留下偶數
result = filter(lambda x: x % 2 == 0, numbers)
list(result)👉 等同於:
[x for x in numbers if x % 2 == 0]✅ 範例 2:過濾長度大於 3 的字串
words = ["apple", "cat", "banana", "dog"]
result = filter(lambda w: len(w) > 3, words)
list(result)✅ 補充:filter 的第一個參數也可以是 None
前面的範例中,我們都是傳入一個 回傳 bool 的一元函數:
result = filter(lambda x: x % 2 == 0, numbers)
list(result)🔍 那如果第一個參數放 None 呢?
result = filter(None, numbers)
list(result)✅ 這是合法的,而且有特殊意義。
✅ filter(None, iterable) 在做什麼?
當第一個參數是 None 時:
filter會直接用元素本身來判斷 True / False(truthiness)
等價於:
filter(lambda x: bool(x), iterable)✅ 範例:移除「假值」
data = [0, 1, 2, "", "hello", None, [], [1, 2]]
list(filter(None, data))輸出:
✅ 被移除的包含:
0""None[]
✅ 對照寫法(幫助理解)
list(filter(lambda x: bool(x), data))✅ 結果完全相同
⚠️ 重要提醒:None 不是預設值
❌ 下面這樣是錯的:
filter(numbers) # TypeError✅ 必須明確寫成:
filter(None, numbers)✅ 什麼時候適合用 filter(None, ...)?
✅ 適合:
- 資料清洗
- 移除
None/ 空值 / 空字串 - 快速留下「有內容」的資料
⚠️ 不適合:
0或""是合法資料的情況
(因為它們會被一起濾掉)
✅ 小結
一般情況下,
filter會吃一個回傳 bool 的函數;
當傳入None時,則改用元素本身的 truthiness 來判斷。
✅ 四、reduce:把多個值「合成一個」
📌 概念
reduce使用 二元函數
反覆把「累積結果 + 下一個元素」合成一個值
📐 使用前要先 import
from functools import reduce✅ 範例 1:全部加總
result = reduce(lambda acc, x: acc + x, numbers)
result輸出:
✅ 範例 2:全部相乘
result = reduce(lambda acc, x: acc * x, numbers)
result✅ 範例 3:指定初始值
result = reduce(lambda acc, x: acc + x, numbers, 10)
result👉 從 10 開始累加
✅ 五、map + filter + reduce 串起來用
🎯 任務:
「把偶數取出來 → 每個乘以 2 → 全部加總」
result = reduce(
lambda acc, x: acc + x,
map(lambda x: x * 2,
filter(lambda x: x % 2 == 0, numbers))
)
result輸出:
✅ 六、什麼時候該用 map / filter / reduce?
✅ 七、常見提醒(很重要)
⚠️ 在 Python 3 中:
map/filter回傳的是 iterator- 要用
list()才會看到結果
✅ 八、一句話總結
map:變形
filter:篩選
reduce:合併
推薦hahow線上學習python: https://igrape.net/30afN