Python 高階函數三劍客: map、filter、reduce #以函數作為參數,或回傳函數的函數

加入好友
加入社群
Python 高階函數三劍客: map、filter、reduce #以函數作為參數,或回傳函數的函數 - 儲蓄保險王

在 Python 中,mapfilterreduce 是三個非常經典的函數式工具
能用「描述做什麼」取代「一步一步怎麼做」,讓程式更簡潔、可讀。

本篇會用白話說明 + 實際範例,一步一步帶你理解。


✅ 一、先建立一份測試資料

numbers = [1, 2, 3, 4, 5, 6]

✅ 二、map:對每個元素「各自做一次」

📌 概念

map 會把 一元函數 套用到「每一個元素」

📐 形式

map(function, iterable)

✅ 範例 1:全部乘以 2

result = map(lambda x: x * 2, numbers)
list(result)

輸出:

Python 高階函數三劍客: map、filter、reduce #以函數作為參數,或回傳函數的函數 - 儲蓄保險王

👉 等同於:

[x * 2 for x in numbers]

✅ 範例 2:數字轉字串

result = map(str, numbers)
list(result)
Python 高階函數三劍客: map、filter、reduce #以函數作為參數,或回傳函數的函數 - 儲蓄保險王

✅ 三、filter:留下「符合條件」的元素

📌 概念

filter 使用 回傳 True / False 的一元函數

📐 形式

filter(function, iterable)

✅ 範例 1:只留下偶數

result = filter(lambda x: x % 2 == 0, numbers)
list(result)
Python 高階函數三劍客: map、filter、reduce #以函數作為參數,或回傳函數的函數 - 儲蓄保險王

👉 等同於:

[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)
Python 高階函數三劍客: map、filter、reduce #以函數作為參數,或回傳函數的函數 - 儲蓄保險王

✅ 四、reduce:把多個值「合成一個」

📌 概念

reduce 使用 二元函數
反覆把「累積結果 + 下一個元素」合成一個值

📐 使用前要先 import

from functools import reduce

✅ 範例 1:全部加總

result = reduce(lambda acc, x: acc + x, numbers)
result

輸出:

Python 高階函數三劍客: map、filter、reduce #以函數作為參數,或回傳函數的函數 - 儲蓄保險王

✅ 範例 2:全部相乘

result = reduce(lambda acc, x: acc * x, numbers)
result
Python 高階函數三劍客: map、filter、reduce #以函數作為參數,或回傳函數的函數 - 儲蓄保險王

✅ 範例 3:指定初始值

result = reduce(lambda acc, x: acc + x, numbers, 10)
result
Python 高階函數三劍客: map、filter、reduce #以函數作為參數,或回傳函數的函數 - 儲蓄保險王

👉 從 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

輸出:

Python 高階函數三劍客: map、filter、reduce #以函數作為參數,或回傳函數的函數 - 儲蓄保險王

✅ 六、什麼時候該用 map / filter / reduce?

Python 高階函數三劍客: map、filter、reduce #以函數作為參數,或回傳函數的函數 - 儲蓄保險王

✅ 七、常見提醒(很重要)

⚠️ 在 Python 3 中:

  • map / filter 回傳的是 iterator
  • 要用 list() 才會看到結果

✅ 八、一句話總結

map:變形
filter:篩選
reduce:合併

推薦hahow線上學習python: https://igrape.net/30afN

加入好友
加入社群
Python 高階函數三劍客: map、filter、reduce #以函數作為參數,或回傳函數的函數 - 儲蓄保險王

儲蓄保險王

儲蓄險是板主最喜愛的儲蓄工具,最喜愛的投資理財工具則是ETF,最喜愛的省錢工具則是信用卡

You may also like...

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *