8.22.2018

Replacements for switch statement in Python?

Replacements for switch statement in Python?


You could use a dictionary:
def f(x):
    return {
        'a': 1,
        'b': 2,
    }[x]

If you'd like defaults you could use the dictionary get(key[, default]) method:
def f(x):
    return {
        'a': 1,
        'b': 2
    }.get(x, 9)    # 9 is default if x not found

沒有留言:

張貼留言