在Python中的match语句,与C/C++, Java中的switch类似,但是功能更强大
简单的匹配
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
在最后的"-“表示一个通配符,匹配所有的。也可以吧多个条件合在一起,用”|“或者"or”
case 401 | 403 | 404:
return "Not allowed"
扩展匹配
# point is an (x, y) tuple
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y={y}")
case (x, 0):
print(f"X={x}")
case (x, y):
print(f"X={x}, Y={y}")
case _:
raise ValueError("Not a point")
这种匹配就类似(x, y) = point这种unpack操作
同样也支持其他unpack操作
def match_sequence2(seq):
match seq:
case [1, *p]:
print(p)
case [3, a, *_]:
print(f"a={a}")
case [_, _, *q]:
print(q)
match_sequence2([1, 2, 3, 4]) # [2, 3, 4]
match_sequence2([3, 4, 5, 6]) # a=4
match_sequence2([2, 3, 4, 5]) # [4, 5]
也可以匹配对象
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def where_is(point):
match point:
case Point(x=0, y=0):
print("Origin")
case Point(x=0, y=abc):
print(f"Y={abc}")
case Point(x=xb, y=0):
print(f"X={xb}")
case Point():
print("Somewhere else")
case _:
print("Not a point")
where_is(Point(3, 4)) # Somewhere else
where_is(Point(0, 4)) # Y=4
where_is(Point(3, 0)) # X=3
也可以用来匹配字典
def match_dict(d):
match d:
case {"name": name, "age": age}:
print(f"name={name},age={age}")
case {"key": _, "value": value}:
print(f"value={value}")
case {"first": _, **rest}:
print(rest)
case _:
pass
d1 = {"name": "ice", "age": 18}
d2 = {"key": "k", "value": "v"}
d3 = {"first": "one", "second": "two", "third": "three"}
match_dict(d1) # name=ice,age=18
match_dict() # value=v
match_dict(d3) # {'second': 'two', 'third': 'three'}