Python Lambda 與高階函式(Higher-Order Functions) | Python

2026/04/24

Python 中,函式是一等公民(First-Class Citizen),可以像變數一樣被傳遞與回傳。Lambda 匿名函式讓你用一行就能定義簡短函式,而 高階函式(Higher-Order Functions)map()filter()sorted() 則能接受函式作為參數,讓程式碼更加簡潔。

Lambda 匿名函式

Lambda 是不需要 def 定義名稱的匿名函式,語法為 lambda 參數: 表達式,只能包含一個表達式並自動回傳結果:

square = lambda x: x ** 2
print(square(5))  # 輸出:25

add = lambda x, y: x + y
print(add(3, 4))  # 輸出:7

Lambda 適合用在需要簡短函式且只使用一次的場景。如果邏輯較複雜,建議使用 def 定義具名函式以提升可讀性。

map() 函式

map() 會將指定的函式套用到可迭代物件(Iterable)的每一個元素上,回傳一個新的迭代器:

numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # 輸出:[1, 4, 9, 16, 25]

def to_celsius(f):
    return round((f - 32) * 5 / 9, 1)

celsius = list(map(to_celsius, [98.6, 212, 32]))
print(celsius)  # 輸出:[37.0, 100.0, 0.0]

filter() 函式

filter() 會根據條件函式過濾元素,只保留讓函式回傳 True 的元素:

numbers = [1, -2, 3, -4, 5, -6]
positives = list(filter(lambda x: x > 0, numbers))
print(positives)  # 輸出:[1, 3, 5]

words = ["hello", "", "world", "", "python"]
non_empty = list(filter(None, words))
print(non_empty)  # 輸出:['hello', 'world', 'python']

sorted() 與 key 參數

sorted()key 參數接受一個函式來決定排序依據,這是 Lambda 最常見的應用場景:

words = ["python", "is", "a", "great", "language"]
print(sorted(words, key=lambda w: len(w)))
# 輸出:['a', 'is', 'great', 'python', 'language']

students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 92},
    {"name": "Charlie", "score": 78},
]
by_score = sorted(students, key=lambda s: s["score"], reverse=True)
for s in by_score:
    print(f'{s["name"]}: {s["score"]}')
# 輸出:Bob: 92, Alice: 85, Charlie: 78

閉包(Closure)

閉包(Closure)是指內部函式能「記住」外部函式的變數,即使外部函式已經執行完畢:

def multiplier(n):
    def multiply(x):
        return x * n
    return multiply

double = multiplier(2)
triple = multiplier(3)
print(double(5))  # 輸出:10
print(triple(5))  # 輸出:15

functools.reduce()

functools.reduce() 會對元素進行累積運算,逐步合併為一個值:

from functools import reduce

numbers = [1, 2, 3, 4, 5]
product = reduce(lambda a, b: a * b, numbers)
print(product)  # 輸出:120

總結

Lambda 匿名函式與高階函式是 Python 函式式程式設計的核心工具。map() 用於轉換元素、filter() 用於過濾元素、sorted() 搭配 key 可靈活排序,而閉包(Closure)讓函式能攜帶狀態。合理運用這些工具能讓程式碼更簡潔,但過於複雜的邏輯仍建議使用具名函式或串列推導式來實現。

Lambda 與高階函式建立在函式基礎之上,建議先閱讀 Python 函數(Functions)入門指南。許多高階函式的效果也能用串列推導式達成,可參考 Python 串列推導式教學