Python中switch语句的替换?

新手上路,请多包涵

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

在其他语言中,我会使用 switchcase 语句,但 Python 似乎没有 switch 语句。在这种情况下推荐的 Python 解决方案是什么?

原文由 Michael Schneider 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 644
2 个回答

下面的原始答案是在 2008 年编写的。从那时起,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 语句比这个简单的例子要强大得多。


您可以使用字典:

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

原文由 Greg Hewgill 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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

原文由 Nick 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏