一、match的理解
def match_test():
age = 18
match age:
case x if x>18:
print(f"{x}是成年人")
case 11|12|13|14:
print(f"11-14是未成年人")
case _:
print(f"{x}是未成年人")
答疑:
case x if x>18:这句执行逻辑:
- x是一个模式变量,他会捕获age的值
- 然后检查守卫条件x>18,根据条件执行后续代码块
说明:
case ["search", pattern, *_]:
*_ 其中*是解包操作符,用于捕获所有的剩余元素,_代表一个贯用的占位符变量名,表示我们并不关心这些值
- "search" 匹配第一个元素
- pattern 捕获第二个元素
- *_ 捕获剩余的所有元素,但我们不会使用这些值
代码示例如下:
# ============= 1. 基础的if-elif-else条件判断 =============
def basic_if_demo():
"""演示基本的if-elif-else用法"""
age = 30
# 1.1 基本的if-elif-else结构
if age >= 19:
print("成年人")
elif age >= 6:
print("青少年")
else:
print("儿童")
# 1.2 条件判断中的类型转换
birth_year = input("请输入出生年份: ") # 输入的是字符串
if int(birth_year) < 2000: # 需要转换为整数才能比较
print("00前")
else:
print("00后")
# ============= 2. 基础的match-case模式匹配 =============
def basic_match_demo():
"""演示基本的match-case用法"""
score = "B"
# 2.1 简单的值匹配
match score:
case "A":
print("优秀")
case "B":
print("良好")
case "C":
print("及格")
case _: # 通配符模式,匹配任何其他情况
print("不及格")
# ============= 3. match-case的高级用法 =============
def advanced_match_demo():
"""演示match-case的高级用法"""
# 3.1 带守卫条件的模式匹配
age = 20
match age:
case x if x > 18: # 使用变量x捕获age的值,并添加条件
print(f"{x}是成年人")
case 11 | 12 | 13 | 14: # 使用 | 表示多个可能的值
print(f"{age}是青少年")
case _: # 默认情况
print(f"{age}是未成年人")
# 3.2 序列模式匹配
command = ["copy", "file1.txt", "file2.txt", "file3.txt"]
match command:
case ["copy", source, dest]: # 匹配包含三个元素的列表
print(f"复制文件:从 {source} 到 {dest}")
case ["copy", source, *targets]: # 使用*捕获剩余所有元素
print(f"复制文件:从 {source} 到多个目标 {targets}")
case _:
print("无效的命令")
# 3.3 对象模式匹配
point = (3, 4)
match point:
case (0, 0): # 匹配原点
print("原点")
case (0, y): # 匹配y轴上的点
print(f"Y轴上的点 y={y}")
case (x, 0): # 匹配x轴上的点
print(f"X轴上的点 x={x}")
case (x, y): # 匹配任意点
print(f"点坐标 ({x}, {y})")
case _:
print("不是有效的点")
# ============= 4. 实际应用示例 =============
def practical_match_demo():
"""展示match-case在实际中的应用"""
# 4.1 命令行参数解析
command = ["search", "python", "--case-sensitive", "--in-files=*.py"]
command1 = ["search", "python", "--in-files=*.py"]
match command1:
case ["search", pattern, *flags] if "--case-sensitive" in flags:
print(f"大小写敏感搜索 {pattern}")
case ["search", pattern, *_]:
print(f"普通搜索 {pattern}")
case _:
print("未知命令")
# 4.2 列表解构示例
items = ["hello", "world", "python", "java", "c++"]
match items:
case []: # 匹配空列表
print("空列表")
case ["hello"]: # 匹配只包含"hello"的列表
print("只有hello")
case ["hello", second, *rest]: # 解构列表
print(f"hello后面是{second},剩余元素是{rest}")
case _:
print("其他情况")
if __name__ == "__main__":
print("=== 基础if演示 ===")
# basic_if_demo() # 注释掉需要输入的部分
print("\n=== 基础match演示 ===")
basic_match_demo()
print("\n=== 高级match演示 ===")
advanced_match_demo()
print("\n=== 实际应用演示 ===")
practical_match_demo()
结果:
=== 基础if演示 ===
=== 基础match演示 ===
良好
=== 高级match演示 ===
20是成年人
复制文件:从 file1.txt 到多个目标 ['file2.txt', 'file3.txt']
点坐标 (3, 4)
=== 实际应用演示 ===
普通搜索 python
hello后面是world,剩余元素是['python', 'java', 'c++']