Myself
  • 1.Python历史
  • 2.安装Python
    • 2.1.Python解释器
  • 3.第一个Python程序
    • 3.1.使用文本编辑器
    • 3.2.输入和输出
  • 4.Python基础
    • 4.1.数据类型和变量
    • 4.2.字符串和编码
    • 4.3.使用list和tuple
    • 4.4.条件判断
    • 4.5.模式匹配
    • 4.6.循环
    • 4.7.使用dict和set
  • 5.函数
    • 5.1.调用函数
    • 5.2.定义函数
    • 5.3.函数的参数
    • 5.4.递归函数
  • 6.高级特性
    • 6.1.切片
    • 6.2.迭代
    • 6.3.列表生成式
    • 6.4.生成器
    • 6.5.迭代器
  • 7.函数式编程
    • 7.1.高阶函数
      • 7.1.1.map/reduce
      • 7.1.2.filter
      • 7.1.3.sorted
    • 7.2.返回函数
    • 7.3.匿名函数
    • 7.4.装饰器
    • 7.5.偏函数
  • 8.模块
    • 8.1.使用模块
    • 8.2.安装第三方模块

搜索结果

没有相关内容~~

4.5.模式匹配

最新修改于 2025-08-07 16:29
当我们用 `if ... elif ... elif ... else ...`判断时,会写很长一串代码,可读性较差。 如果要针对某个变量匹配若干种情况,可以使用 `match`语句。 例如,某个学生的成绩只能是 `A`、`B`、`C`,用 `if`语句编写如下: ```python score = 'B' if score == 'A': print('score is A.') elif score == 'B': print('score is B.') elif score == 'C': print('score is C.') else: print('invalid score.') ``` []( "复制到剪贴板") 如果用 `match`语句改写,则改写如下: ```python score = 'B' match score: case 'A': print('score is A.') case 'B': print('score is B.') case 'C': print('score is C.') case _: # _表示匹配到其他任何情况 print('score is ???.') ``` []( "复制到剪贴板") 使用 `match`语句时,我们依次用 `case xxx`匹配,并且可以在最后(且仅能在最后)加一个 `case _`表示“任意值”,代码较 `if ... elif ... else ...`更易读。 ### 复杂匹配 `match`语句除了可以匹配简单的单个值外,还可以匹配多个值、匹配一定范围,并且把匹配后的值绑定到变量: ```python age = 15 match age: case x if x < 10: print(f'< 10 years old: {x}') case 10: print('10 years old.') case 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18: print('11~18 years old.') case 19: print('19 years old.') case _: print('not sure.') ``` []( "复制到剪贴板") 在上面这个示例中,第一个 `case x if x < 10`表示当 `age < 10`成立时匹配,且赋值给变量 `x`,第二个 `case 10`仅匹配单个值,第三个 `case 11|12|...|18`能匹配多个值,用 `|`分隔。 可见,`match`语句的 `case`匹配非常灵活。 ### 匹配列表 `match`语句还可以匹配列表,功能非常强大。 我们假设用户输入了一个命令,用 `args = ['gcc', 'hello.c']`存储,下面的代码演示了如何用 `match`匹配来解析这个列表: ```python args = ['gcc', 'hello.c', 'world.c'] # args = ['clean'] # args = ['gcc'] match args: # 如果仅出现gcc,报错: case ['gcc']: print('gcc: missing source file(s).') # 出现gcc,且至少指定了一个文件: case ['gcc', file1, *files]: print('gcc compile: ' + file1 + ', ' + ', '.join(files)) # 仅出现clean: case ['clean']: print('clean') case _: print('invalid command.') ``` []( "复制到剪贴板") 第一个 `case ['gcc']`表示列表仅有 `'gcc'`一个字符串,没有指定文件名,报错; 第二个 `case ['gcc', file1, *files]`表示列表第一个字符串是 `'gcc'`,第二个字符串绑定到变量 `file1`,后面的任意个字符串绑定到 `*files`(符号 `*`的作用将在[函数的参数](https://liaoxuefeng.com/books/python/function/parameter/index.html)中讲解),它实际上表示至少指定一个文件; 第三个 `case ['clean']`表示列表仅有 `'clean'`一个字符串; 最后一个 `case _`表示其他所有情况。 可见,`match`语句的匹配规则非常灵活,可以写出非常简洁的代码。
开始访问