[Python] match-case: Python 中的 Switch-case
- 2022.02.15
- Python
match Statement
match subject: case <pattern_1>: <action_1> case <pattern_2>: <action_2> case <pattern_3> | <pattern_4>: # multi-patterns <action_3_4> case _: # otherwise <action_wildcard>
等同:
if subject == <pattern_1>: <action_1> elif subject == <pattern_2>: <action_2> elif subject == <pattern_3> or subject ==<pattern_4>: <action_3_4> else: <action_wildcard>
等同 C 的 switch-case :
switch(subject): case <pattern_1>: <action_1> break case <pattern_2>: <action_2> break case <pattern_3>: case <pattern_4>: <action_3_4> break default: <action_wildcard>
Patterns can be Used to Bind Variables
match point: # point is a (x, y) tuple case (0, 0): // ... case (0, y): // ... case (x, 0): // ... case (x, y): // ... case _: raise ValueError("Not a point")
case … if …:
Last Updated on 2024/12/02 by A1go