1、基本语法使用
在Python 3.10及更高版本中,引入了一种新的模式匹配语法,即match语句。这种语法类似于其他编程语言中的switch语句,但更强大和灵活,因为它允许对值进行结构化的模式匹配。
(1)整型数值匹配
match语句会检查data的值,并根据匹配的模式执行相应的代码块。case 0:表示如果data等于0,则执行该代码块。case _:是一个通配符模式,匹配任何值。
data = 22
# 使用 match 语句进行模式匹配
match data:
case 0:
print("Zero")
case _:
print(f"Not zero: {data}")
(2)字符串匹配
match语句会检查data的值,并根据匹配的模式执行相应的代码块。
data = "bye"
# 使用 match 语句进行多个模式匹配
match data:
case "hello":
print("Greeting detected")
case "bye":
print("Farewell detected")
case _:
print("Unknown message")
(3)元组值匹配
据匹配的模式执行相应的代码块。同时,可以通过(x, y)捕获元组中的值,并在后续代码中使用。
point = (1, 2)
# 使用 match 语句捕获值
match point:
case (x, y) if x == y:
print(f"Point is on the line y=x at ({x}, {y})")
case (x, y):
print(f"Point is at ({x}, {y})")
(4)嵌套字典值匹配
根据匹配的模式执行相应的代码块。这里使用了嵌套的字典模式进行匹配。
shape = {"type": "circle", "radius": 5}
# 使用 match 语句进行嵌套模式匹配
match shape:
case {"type": "circle", "radius": r}:
print(f"Circle with radius {r}")
case {"type": "rectangle", "width": w, "height": h}:
print(f"Rectangle with width {w} and height {h}")
case _:
print("Unknown shape")
(5)复杂字典匹配
复杂的字典模式进行匹配,并捕获了相应的值。
status = {"code": 200, "message": "OK"}
# 使用 match 语句进行复杂模式匹配
match status:
case {"code": 200, "message": msg}:
print(f"Success: {msg}")
case {"code": 404, "message": msg}:
print(f"Not Found: {msg}")
case {"code": code, "message": msg}:
print(f"Error {code}: {msg}")
case _:
print("Unknown status")
(6)结构里多种类型匹配
data=eval(input("请输入要匹配的数据:"))
match data:
case {'name':'ysj' ,'age' : 20}:
print('字典')
case [10,20,30]:
print('列表')
case (10,20,40):
print('元组')
case _:
print('相当于多重if中的else' )
输入helo报错,原因是把hello当变量了,eval去掉了一次引号
带入引号输入
2、字典新特性:字典合并运算 |
d1={'a':10, 'b':20}
d2={'c ':30, 'd':40, 'e' :50}
merged_dict=d1|d2
print(merged_dict)
3、同步迭代
概念:同步迭代是指同时遍历多个可迭代对象,并且每次迭代都返回来自每个对象的元素。在Python中,可以使用zip函数来实现同步迭代。
用法:将多个可迭代对象作为zip函数的参数,它会返回一个迭代器,该迭代器每次迭代都返回一个包含来自每个输入迭代器的元素的元组。
# 创建两个列表,分别表示up主和热度
name = ['HOPE', '孟焰', '沈焰' ,'kailo']
Popular_level = [3, 5, 1, 2, 9 ]
# 使用zip函数进行同步迭代
for n, p in zip(name, Popular_level):
match n, p:
case 'HOPE', 3:
print('HOPE的热度为3')
case '孟焰', 5:
print('孟焰的热度为5')
case '沈焰', 1:
print('沈焰的热度为1')
case 'lll', 0:
print('没热度')
case _:
print('太高热')