Python 內置高階函數 map、any、all 組合使用,能以極簡潔、聲明式風格解決數據處理與判斷問題。本文以「密碼複雜度驗證」為例,拆解這三個函數的協作邏輯,並拋出進階思考題。
| 函數 | 作用 | 等價邏輯 |
|---|---|---|
map(func, iterable) | 對可迭代對象每個元素應用 func,返回迭代器(Py3) | (func(x) for x in iterable) |
any(iterable) | 任一元素為真即返回 True | 逻辑「或」累積 |
all(iterable) | 所有元素為真才返回 True | 逻辑「與」累積 |
需求:密碼必須同時包含**大寫字母、小寫字母、數字、特殊符號**(非字母數字)。
def valid(pwd):
has_upper = any(map(str.isupper, pwd))
has_lower = any(map(str.islower, pwd))
has_digit = any(map(str.isdigit, pwd))
has_special = not all(map(str.isalnum, pwd)) # 存在非字母數字字符
return all([has_upper, has_lower, has_digit, has_special])
map(str.isupper, pwd) → 對密碼每字符檢測是否大寫,產生布爾序列:[False, True, False, ...]any(...) → 序列中任一 True 即返回 True,即「存在大寫」。str.isalnum 判斷是否字母或數字,all(map(str.isalnum, pwd)) 為 True 表示**全是**字母數字 → 取反得「存在特殊符號」。all([...]) 要求四條件**全滿足**。any/all 遇到決定性結果立即停止,性能優於手寫循環。若規則變為:「四項條件中**任意滿足兩項**即通過」,如何用類似風格實現?
歡迎在評論區分享你的一行式解法!
# 檢查列表中是否有重複元素
has_dup = len(set(lst)) != len(lst)
# 所有元素滿足條件
all(x > 0 for x in numbers)
# 任一元素滿足條件
any(x % 2 == 0 for x in numbers)
# 多條件組合:所有用戶年齡>=18 且 至少一個是 VIP
all(u.age >= 18 for u in users) and any(u.is_vip for u in users)
map 做轉換,any/all 做聚合判斷,三者結合是 Python 函數式編程的「瑞士軍刀」。掌握它們,能寫出更優雅、高效、可維護的代碼。