Python 简明教程

Python - Match-Case Statement

Python match-case Statement

Python match-case 语句取一个表达式,并将它的值与作为一或多个案例块给出的连续模式进行比较。仅执行第一个匹配的模式。也可以从值中提取组成部分(序列元素或对象属性)到 variables 中。

A Python match-case statement takes an expression and compares its value to successive patterns given as one or more case blocks. Only the first pattern that matches gets executed. It is also possible to extract components (sequence elements or object attributes) from the value into variables.

随着 Python 3.10 的发布,引入了称为 match-case 的模式匹配技术,它类似于 C/C/Java 等中可用的 *switch-case* 构造。它的基本用法是将变量与一个或多个值进行比较。它更类似于类似 Rust 或 Haskell 中的模式匹配,而不是 C 或 C 中的 switch 语句。

With the release of Python 3.10, a pattern matching technique called match-case has been introduced, which is similar to the switch-case construct available in C/C/Java etc. Its basic use is to compare a variable against one or more values. It is more similar to pattern matching in languages like Rust or Haskell than a switch statement in C or C.

Syntax

以下是 Python 中匹配-情况语句的语法 -

The following is the syntax of match-case statement in Python -

match variable_name:
   case 'pattern 1' : statement 1
   case 'pattern 2' : statement 2
   ...
   case 'pattern n' : statement n

Example

以下代码有一个名为 weekday() 的函数。它接收一个整数参数,将其与所有可能的星期几数字值进行匹配,并返回相应的星期名称。

The following code has a function named weekday(). It receives an integer argument, matches it with all possible weekday number values, and returns the corresponding name of day.

def weekday(n):
   match n:
      case 0: return "Monday"
      case 1: return "Tuesday"
      case 2: return "Wednesday"
      case 3: return "Thursday"
      case 4: return "Friday"
      case 5: return "Saturday"
      case 6: return "Sunday"
      case _: return "Invalid day number"
print (weekday(3))
print (weekday(6))
print (weekday(7))

执行此代码后,会生成以下输出 −

On executing, this code will produce the following output −

Thursday
Sunday
Invalid day number

该函数中的最后一个 case 语句以“_”作为要比较的值。它充当通配符 case,如果所有其他 case 都不成立,它将执行。

The last case statement in the function has "_" as the value to compare. It serves as the wildcard case, and will be executed if all other cases are not true.

Combined Cases in Match Statement

有时候可能会出现这样的情况:对于多个情况,必须采取类似的操作。为此,您可以将情况与由 “|” 符号表示的 OR 运算符结合起来。

Sometimes, there may be a situation where for more than one cases, a similar action has to be taken. For this, you can combine cases with the OR operator represented by "|" symbol.

Example

下面的代码显示了如何在匹配语句中合并情况。它定义了一个名为 access() 的函数,并有一个字符串参数,表示用户的名称。对于 admin 或 manager 用户,系统授予完全访问权限;对于 Guest,访问权限受到限制;对于其他用户,没有访问权限。

The code below shows how to combine cases in match statement. It defines a function named access() and has one string argument, representing the name of the user. For admin or manager user, the system grants full access; for Guest, the access is limited; and for the rest, there’s no access.

def access(user):
   match user:
      case "admin" | "manager": return "Full access"
      case "Guest": return "Limited access"
      case _: return "No access"
print (access("manager"))
print (access("Guest"))
print (access("Ravi"))

运行上面的代码后,会显示以下结果 −

On running the above code, it will show the following result −

Full access
Limited access
No access

List as the Argument in Match Case Statement

由于 Python 可以将表达式与任何 literal 匹配,因此您可以使用 list 作为情况值。此外,对于列表中变数的项目数,它们可以通过 “*” 运算符解析为序列。

Since Python can match the expression against any literal, you can use a list as a case value. Moreover, for variable number of items in the list, they can be parsed to a sequence with "*" operator.

Example

在此代码中,我们使用列表作为匹配情况语句中的参数。

In this code, we use list as argument in match case statement.

def greeting(details):
   match details:
      case [time, name]:
         return f'Good {time} {name}!'
      case [time, *names]:
         msg=''
         for name in names:
            msg+=f'Good {time} {name}!\n'
         return msg

print (greeting(["Morning", "Ravi"]))
print (greeting(["Afternoon","Guest"]))
print (greeting(["Evening", "Kajal", "Praveen", "Lata"]))

执行此代码后,会生成以下输出 −

On executing, this code will produce the following output −

Good Morning Ravi!
Good Afternoon Guest!
Good Evening Kajal!
Good Evening Praveen!
Good Evening Lata!

Using "if" in "Case" Clause

通常,Python 将表达式与文本情况匹配。但是,它允许您在情况子句中包含 if statement 以进行匹配变量的条件计算。

Normally Python matches an expression against literal cases. However, it allows you to include if statement in the case clause for conditional computation of match variable.

Example

在以下示例中,函数参数是 amount 和 duration 的一个列表,而 intereset 要根据金额小于或大于 10000 来计算。条件包含在 case 子句中。

In the following example, the function argument is a list of amount and duration, and the intereset is to be calculated for amount less than or more than 10000. The condition is included in the case clause.

def intr(details):
   match details:
      case [amt, duration] if amt<10000:
         return amt*10*duration/100
      case [amt, duration] if amt>=10000:
         return amt*15*duration/100
print ("Interest = ", intr([5000,5]))
print ("Interest = ", intr([15000,3]))

执行此代码后,会生成以下输出 −

On executing, this code will produce the following output −

Interest = 2500.0
Interest = 6750.0