Python match-case 是 Python 3.10 中引入的一种新的语言结构,用于模式匹配(Pattern Matching)。它提供了一种更强大和直观的方式来处理多个条件的情况,并且比传统的 if-elif-else 结构更清晰和简洁。
什么是match-case语句
对于来自 C/C++ 或 Java 等语言的开发人员来说,有一个称为Switch Case 的条件语句。这个Match-Case就是Python的Switch Case,在Python 3.10中引入。这里我们必须首先传递一个参数,然后尝试检查在哪种情况下该参数得到满足。如果我们找到匹配项,会执行一些操作,如果根本没有匹配项,我们会做其他事情。
基本语法
match value:
case pattern1:
# 处理与 pattern1 匹配的情况
# 可以使用匹配的值,例如 pattern1 中的变量
case pattern2:
# 处理与 pattern2 匹配的情况
# 可以使用匹配的值,例如 pattern2 中的变量
case ...:
# 处理其他模式匹配情况
case _:
# 处理没有匹配任何模式的情况
match 语句用于匹配一个值(通常是变量或表达式的结果),然后根据匹配的情况执行相应的代码块。在 match 语句中,可以定义多个 case 分支,每个分支都包含一个模式(pattern)和与该模式匹配时执行的代码块。
例子
def get_color_name(color_code):
match color_code:
case 1:
return "Red"
case 2:
return "Green"
case 3:
return "Blue"
case _:
return "Unknown"
color_code = 2
color_name = get_color_name(color_code)
print(f"Color with code {color_code} is {color_name}")
在匹配语句中使用 Python OR
匹配语句仅用于匹配模式和特定关键字或参数。但您可以在 match 语句中使用‘|’运算符。
def provideAccess(user) :
return {
"username" : user ,
"password" : "admin"
}
def runMatch() :
user = str(input("Write your username -: "))
# match statement
match user :
case "Om" | "Vishal" :
print("You are not allowed to access the database !")
case "Rishabh" :
print("You are allowed to access the database !")
data = provideAccess("Rishabh")
print(data)
case _ :
print("You are not a company memeber , you are not \
allowed to access the code !")
if __name__ == "__main__" :
for _ in range(2) :
runMatch()
输出:
在匹配语句中使用 Python If
在Python的match-case语句中,你可以结合使用if语句来进一步处理匹配的情况。这样可以允许更复杂的条件逻辑。
在此示例中,它检查用户输入的用户名是否在 allowedDataBaseUsers 列表中。如果用户名是 “Rishabh” 且在列表中,就允许访问数据库,否则拒绝访问。
def provideAccess(user):
return {
"username": user,
"password": "admin"
}
def runMatch():
user = str(input("Write your username -: "))
allowedDataBaseUsers = ["Rishabh"]
match user:
case "Rishabh" if user in allowedDataBaseUsers:
print("You are allowed to access the database !")
data = provideAccess("Rishabh")
print(data)
case _:
print("You are not a company memeber , \
you are not allowed to access the code !")
if __name__ == "__main__":
for _ in range(2):
runMatch()
输出:
在match语句中使用Python字典
这里的第一种情况匹配字典的键和值,只有一个值和字典。第二种情况匹配多个键,键和值必须驻留在字典中,如果有任何放错的值或任何不存在的键且与实际字典和值不匹配,则这种情况将被丢弃。并且对于第三种情况,我们刚刚检查了名为名称、语言和框架的键,并且它们各自的变量是用相同的名称创建的,您可以轻松更改它们。
def runMatch(dictionary):
match dictionary:
case {"name": "Om"}:
print("This matches only for one key ,\
that is if they key exists with the pair \
value then this block will be selected !")
case {"framework": "Django", "language": "Python"}:
print("This one matches multiple keys and values . !")
case {"name": name, "language": language,
"framework": framework}:
print(f"The person's name is {name} , \
the language he uses is {language}\
and the framework he uses is {framework} !")
case _:
print("Matches anything !")
if __name__ == "__main__":
a = {
"name": "Om",
"language": "Python",
"framework": "Django",
}
runMatch(a)
a["name"] = "Rishabh"
runMatch(a)
a["language"] = "C++"
runMatch(a)
输出: