• 预备
  • 基础语法
  • 容器类型
  • 函数
  • 面向对象
  • 输入输出
  • 进程控制
  • 线程控制
  • 正则表达式
  • 网络编程
  • 图形界面
  • 常见问题
  • API 帮助手册

  • 设置

2014

10 分钟

#模式匹配

#元组或列表的模式匹配

使用元组或列表形式的模式,可以匹配元组或列表:

students:list[str] = ["Tom", "Jerry", "Spike"] # 列表 match students: case (student1, student2): # 匹配两个元素的元组或列表 print("有两名学生,分别是", student1, student2) case (_, _, _, _, *other): # 匹配四个以上元素的元组或列表 print("有四名以上学生,分别是", students) case ("Tuffy", student1, student2): # 匹配三个元素且第一个元素是 Tuffy 的元组或列表 print("Tuffy 后面的座位是", student1, student2) case (student1, student2, "Spike"): # 匹配三个元素且第三个元素是 Spike 的元组或列表 print("Spike 前面的座位是", student1, student2) case _: print("BBQ")
Loading...

模式既可以写成元组的形式,也可以写成列表的形式,甚至可写成序列形式(无括号)。
但无论写成哪种形式,模式都不区分元组和列表,既能匹配元组,也能匹配列表,。

如果需要进行区分,可以组合其它模式共同实现。

students:list[str] = ("Tom", "Jerry", "Spike") # 列表 match students: case tuple((student1, student2, student3)): # 两层括号,外层为函数调用,内存为元组形式的模式 print("三个元素的元组") case list((student1, student2, student3)): print("三个元素的列表") case _: print("BBQ")
Loading...

#字典的模式匹配

使用字典形式的模式,可以匹配字典:

score_list:dict[str,int] = { 'Tom': 88, 'Jerry': 99, 'Spike': 66 } match score_list: case {"Tuffy": score}: # 匹配含有 Tuffy 键的字典 print("Toffy 的成绩是", score) case {"Jerry": str(score)}: # 匹配 Jerry 键对应的值类型为 str 的字典 print("Toffy 的成绩是", score) case {"Tom": 88, "Jerry": score}: # 匹配 Tom 键对应的值为 77 且含有 Jerry 键的字典 print("Tom 成绩 88 的那次考试,Jerry 的成绩是", score) case _: print("BBQ")
Loading...

#集合的模式匹配

集合 不能作为模式,仅能用空集来判断变量是不是集合,但使用 if 或者 isinstance 判断更加方便:

students:set[str] = {"Tom", "Jerry", "Spike"} # 集合 match students: case set(): print("集合")
Loading...

创建于 2025/4/11 03:41:55

更新于 2025/4/29 18:31:56