在 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)
✅ 四、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










近期留言