Python >= 3.10
哇,Python 3.10+ 现在有一个 match/case 语法,类似于 switch/case 等等!
PEP 634 -- Structural Pattern Matching
match/case的精选功能
1 - 匹配值:
匹配值类似于另一种语言中的简单switch/case:
match something:
case 1 | 2 | 3:
# Match 1-3.
case _:
# Anything else.
#
# Match will throw an error if this is omitted
# and it doesn't match any of the other patterns.
2 - 匹配结构模式:
match something:
case str() | bytes():
# Match a string like object.
case [str(), int()]:
# Match a `str` and an `int` sequence
# (`list` or a `tuple` but not a `set` or an iterator).
case [_, _]:
# Match a sequence of 2 variables.
# To prevent a common mistake, sequence patterns don’t match strings.
case {"bandwidth": 100, "latency": 300}:
# Match this dict. Extra keys are ignored.
3 - 捕获变量
解析一个对象;将其保存为变量:
match something:
case [name, count]
# Match a sequence of any two objects and parse them into the two variables.
case [x, y, *rest]:
# Match a sequence of two or more objects,
# binding object #3 and on into the rest variable.
case bytes() | str() as text:
# Match any string like object and save it to the text variable.
捕获变量在解析可能以多种不同模式之一出现的数据(例如 JSON 或 HTML)时非常有用。
捕获变量是一个特性。但这也意味着您只需要使用带点的常量(例如:COLOR.RED)。否则,常量将被视为捕获变量并被覆盖。
More sample usage:
match something:
case 0 | 1 | 2:
# Matches 0, 1 or 2 (value).
print("Small number")
case [] | [_]:
# Matches an empty or single value sequence (structure).
# Matches lists and tuples but not sets.
print("A short sequence")
case str() | bytes():
# Something of `str` or `bytes` type (data type).
print("Something string-like")
case _:
# Anything not matched by the above.
print("Something else")
Python <= 3.9
我最喜欢的开关/案例 Python 配方是:
choices = {'a': 1, 'b': 2}
result = choices.get(key, 'default')
对于简单的场景,简短而简单。
与 11 多行 C 代码相比:
// C Language version of a simple 'switch/case'.
switch( key )
{
case 'a' :
result = 1;
break;
case 'b' :
result = 2;
break;
default :
result = -1;
}
您甚至可以使用元组分配多个变量:
choices = {'a': (1, 2, 3), 'b': (4, 5, 6)}
(result1, result2, result3) = choices.get(key, ('default1', 'default2', 'default3'))