Remplacements pour la déclaration de commutation en Python

Mots clés : pythonswitch-statementpython

meilleur 5 Réponses Remplacements pour la déclaration de commutation en Python

vote vote

92

def f(x):     match x:         case 'a':             return 1         case 'b':             return 2         case _:                     return 0   # 0 is the default case if x is not found 
def f(x):     return {         'a': 1,         'b': 2,     }[x] 
vote vote

88

def f(x):     return {         'a': 1,         'b': 2     }.get(x, 9)    # 9 is default if x is not found 
vote vote

75

result = {   'a': lambda x: x * 5,   'b': lambda x: x + 7,   'c': lambda x: x - 2 }[value](x) 
vote vote

68

if x == 'a':     # Do the thing elif x == 'b':     # Do the other thing if x in 'bc':     # Fall-through by not using elif, but now the default case includes case 'a'! elif x in 'xyz':     # Do yet another thing else:     # Do the default 
vote vote

54

match something:     case 0 | 1 | 2:         # Matches 0, 1 or 2         print("Small number")     case [] | [_]:         # Matches an empty or single value sequence         # Matches lists and tuples but not sets         print("A short sequence")     case str() | bytes():         # Something of `str` or `bytes` type         print("Something string-like")     case _:         # Anything not matched by the above         print("Something else") 
choices = {'a': 1, 'b': 2} result = choices.get(key, 'default') 
// 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')) 

Questions similaires