Python中switch语句的替代方案?
Python中switch语句的替代方案?
这个问题的答案是一个社区合作。编辑现有答案以改进此帖子。目前不接受新的答案或互动。
我想在Python中编写一个函数,根据输入索引的值返回不同的固定值。
在其他语言中,我会使用switch
或case
语句,但Python似乎没有switch
语句。在这种情况下,Python推荐的解决方案是什么?
admin 更改状态以发布 2023年5月20日
如果您想要默认值,可以使用字典的get(key[, default])
函数:
def f(x): return { 'a': 1, 'b': 2 }.get(x, 9) # 9 will be returned default if x is not found
Python 3.10 (2021) 引入了match
-case
语句,为Python提供了一流的“switch”实现。例如:
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
语句比这个简单示例要强大得多。
下面的原始答案是在2008年编写的,在match
-case
出现之前:
你可以使用一个字典:
def f(x): return { 'a': 1, 'b': 2, }[x]