Python中替换switch语句的方法?

1717 投票
44 回答
2280405 浏览
提问于 2025-04-11 09:18

我想在Python里写一个函数,根据输入的索引值返回不同的固定值。

在其他编程语言中,我会使用switchcase语句来实现这个功能,但Python似乎没有switch语句。在这种情况下,有什么推荐的Python解决方案呢?

44 个回答

487

我一直喜欢这样做

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

来自这里

1589

如果你想要设置默认值,可以使用字典里的 get(key[, default]) 函数:

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

Python 3.10(2021年)引入了 match-case 语句,这个语句可以看作是Python中的一种“开关”功能,使用起来非常方便。例如:

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

其实,match-case 语句的功能远比这个简单的例子要强大得多。


如果你需要支持Python 3.9及以下版本,可以用字典来代替:

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

撰写回答