在程式設計中有兩大主要風格:
nums = [1, 2, 3, 4, 5]
squares = []
for n in nums:
squares.append(n ** 2)
print(squares)
# [1, 4, 9, 16, 25]
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda n: n ** 2, nums))
print(squares)
# [1, 4, 9, 16, 25]
這樣的寫法像是在「描述規則」而不是「自己控制流程」。好處是簡潔、可讀性高,而且能更容易搭配其他函數組合。
語法:
map(function, iterable)
將一個函式套用到序列中的每個元素。
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, nums))
print(squares)
輸出:
[1, 4, 9, 16, 25]
語法:
filter(function, iterable)
nums = [1, 2, 3, 4, 5, 6, 7, 8]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even)
輸出:
[2, 4, 6, 8]
語法:
reduce(function, iterable)
來自 functools 模組,用於把序列中的值依序「合併」起來。
from functools import reduce
nums = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, nums)
print(product) # 1*2*3*4*5=120
reduce 在 Python 裡比較少用,因為很多情況用 for 或 sum() 就能達成,但在需要「把所有元素合併成一個值」的時候很方便。
lambda 可以建立臨時的小函式,不需要用 def:
add = lambda a, b: a + b
print(add(3, 5)) # 8
等同於:
def add(a, b):
return a + b
語法速記
lambda x: x + 1 # 一個參數
lambda x, y=0: x + y # 預設參數
lambda *args: sum(args) # 可變參數
lambda x, **kw: kw.get('k', x) # 關鍵字參數
限制: 只能寫「運算式」,不能有多行、return/for/while/print(print 可當函式呼叫,但不建議在 lambda 放副作用)、try…等「敘述」。
nums = [1, 2, 3, 4, 5]
# map:批次轉換
squares = list(map(lambda x: x**2, nums)) # [1, 4, 9, 16, 25]
# filter:條件篩選
evens = list(filter(lambda x: x % 2 == 0, nums)) # [2, 4]
# reduce:累積運算
from functools import reduce
product = reduce(lambda a, b: a * b, nums) # 120
找出 1~30 中能被 3 整除的平方數
nums = range(1, 31)
result = list(
map(lambda x: x ** 2,
filter(lambda x: x % 3 == 0, nums))
)
print(result)
輸出:
[9, 36, 81, 144, 225, 324, 441, 576, 729]
今天學到 map、filter、reduce 搭配 lambda,感覺就像是「把迴圈濃縮成一個公式」。用一行就能表達「轉換」、「篩選」、「累積」的邏輯。不過如果邏輯太複雜,塞在一行反而會讓程式難以閱讀,所以要拿捏使用時機。
明天要進入物件導向 OOP 的基礎,學習 class 與 object。這是 Python 與 Java 都有的核心觀念,只是 Python 的語法更簡潔。透過 OOP 可以把資料與功能包裝成「物件」,更貼近真實世界的思維,也能讓程式結構更清晰、更容易擴充。