以下是 Python 中 lambda
、map
、filter
和 reduce
的詳細功能介紹及用法總結,涵蓋基礎語法、高頻場景和示例代碼。
一、lambda
匿名函數
功能
- 用于快速定義一次性使用的匿名函數。
- 不需要顯式命名,適合簡化小規模邏輯。
語法
lambda 參數1, 參數2, ...: 表達式
示例
# 定義加法函數
add = lambda a, b: a + b
print(add(3, 5)) # 輸出 8# 作為參數傳遞給其他高階函數
squared = map(lambda x: x**2, [1, 2, 3])
print(list(squared)) # 輸出 [1, 4, 9]
二、map
映射
功能
- 對序列中的每個元素執行指定操作,生成新的迭代器。
語法
map(函數, 可迭代對象)
示例
# 將列表中的每個數平方
numbers = [1, 2, 3, 4]
result = map(lambda x: x**2, numbers)
print(list(result)) # 輸出 [1, 4, 9, 16]# 處理多序列(按最短序列長度)
texts = ["apple", "banana", "cherry"]
sizes = [5, 6]
result = map(lambda a, b: (a, len(a), b), texts, sizes)
print(list(result)) # 輸出 [('apple',5,5), ('banana',6,6)]
三、filter
過濾
功能
- 根據條件篩選序列中滿足要求的元素,生成新的迭代器。
語法
filter(條件函數, 可迭代對象)
示例
# 過濾偶數
numbers = [1, 2, 3, 4, 5, 6]
even = filter(lambda x: x % 2 == 0, numbers)
print(list(even)) # 輸出 [2, 4, 6]# 過濾非空字符串
words = ["hello", "", "world", None, " "]
valid_words = filter(lambda s: s and s.strip(), words)
print(list(valid_words)) # 輸出 ['hello', 'world']
四、reduce
累積
功能
- 將序列中的元素通過函數累積計算,最終返回一個結果(需導入
functools
模塊)。
語法
from functools import reduce
reduce(累積函數, 可迭代對象, [初始值])
示例
from functools import reduce# 累加元素
numbers = [1, 2, 3, 4]
sum_result = reduce(lambda a, b: a + b, numbers) # 等效于 1+2+3+4
print(sum_result) # 輸出 10# 求最大值
max_result = reduce(lambda a, b: a if a > b else b, numbers)
print(max_result) # 輸出 4# 字符串拼接
words = ["I", "love", "Python"]
sentence = reduce(lambda a, b: f"{a} {b}", words)
print(sentence) # 輸出 "I love Python"# 帶初始值
product = reduce(lambda a, b: a * b, [2, 3, 4], 1) # 1*2*3*4=24
print(product) # 輸出 24
五、實際應用場景
1. 數據清洗(filter
+ lambda
)
data = ["10.5", "error", "20.3", "NaN", "15.7"]# 過濾無法轉換為浮點數的元素
clean_data = list(filter(lambda x: x.replace('.', '', 1).isdigit(), data))
print(clean_data) # 輸出 ['10.5', '20.3', '15.7']
2. 多條件轉換(map
+ lambda
)
prices = [100, 200, 300]# 根據價格生成帶稅結果(稅率 8%)
taxed_prices = list(map(lambda p: (p, p * 1.08), prices))
print(taxed_prices) # 輸出 [(100,108.0), (200,216.0), (300,324.0)]
3. 復雜累積(reduce
)
# 將二維列表扁平化
nested_list = [[1, 2], [3, 4], [5, 6]]
flattened = reduce(lambda a, b: a + b, nested_list)
print(flattened) # 輸出 [1, 2, 3, 4, 5, 6]
六、對比列表推導式
方法 | 用途 | 優點 | 缺點 |
---|---|---|---|
map + lambda | 統一處理每個元素 | 簡潔,適合小規模操作 | 難以處理復雜邏輯 |
列表推導式 | 生成新列表 | 直觀,支持條件分支 | 大量計算時內存占用可能較高 |
filter + lambda | 篩選元素 | 直接表達過濾條件 | 多條件篩選語法稍復雜 |
生成器表達式 | 惰性計算大數據 | 內存高效,支持流式處理 | 結果只能遍歷一次 |
七、注意事項
- 可讀性優先:如果邏輯復雜,建議使用顯式命名的普通函數。
- 性能權衡:
map
/filter
在大型數據集下可能比列表推導式更高效(尤其是結合生成器時)。 - Python 3 的迭代器:
map
、filter
返回迭代器,直接打印時需轉換為列表(如list(map(...))
)。 reduce
替代方案:簡單累加建議使用sum()
、max()
等內置函數。
掌握這些工具后,可以大幅簡化迭代操作代碼!建議優先使用列表推導式和生成器表達式,必要時結合 lambda
、map
、filter
、reduce
。