萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 內建函式 map、any、all 實戰:密碼強度驗證一行搞定

前言

Python 的 map、any、all 三劍客,配合字串方法,能以極簡潔的函數式風格解決許多判斷問題。本文以「密碼複雜度檢查」為例,逐步拆解其運作邏輯。

需求:密碼必須同時包含

  • 至少一個大寫字母
  • 至少一個小寫字母
  • 至少一個數字
  • 至少一個特殊符號(非字母數字)

一行解決方案

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)對每字元執行 .isupper()iterator of bool
any(...)任一為 True 即回 Truebool
all(map(str.isalnum, pwd))全為英數字則 Truebool
not all(...)存在非英數字(特殊符號)bool
all([...])四項條件全滿足bool

進階挑戰:四項條件只要滿足兩項即通過

提示:將四個布林值加總,判斷 sum >= 2。

def valid_v2(pwd):
    checks = [
        any(map(str.isupper, pwd)),
        any(map(str.islower, pwd)),
        any(map(str.isdigit, pwd)),
        not all(map(str.isalnum, pwd))
    ]
    return sum(checks) >= 2

效能與可讀性權衡

  • map + any/all 為惰性求值,遇真/偽即短路,效能佳。
  • 若邏輯極度複雜,顯式迴圈反而更易維護;善用 itertools 組合更強大。

結語

掌握 map/any/all,能將許多「逐項檢查」轉化為宣告式一行代碼,既優雅又高效。下次遇到多條件判斷,試著用這三劍客重構一下吧!

copyright © 萬盛學電腦網 all rights reserved