我想用Python编写一个函数,根据输入索引值返回不同的固定值。
在其他语言中,我会使用switch
或case
语句,但是Python语言似乎没有switch
语句。在此场景中,推荐的Python解决方案是什么?
发布于 2008-09-13 00:38:24
下面的原始答案是在2008年写的。从那时起,Python3.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
语句比这个简单的示例要强大得多。
你可以使用字典:
def f(x):
return {
'a': 1,
'b': 2,
}[x]
发布于 2008-09-19 23:45:15
如果您喜欢默认设置,可以使用字典get(key[, default])
方法:
def f(x):
return {
'a': 1,
'b': 2
}.get(x, 9) # 9 is default if x is not found
发布于 2008-09-13 00:41:46
我一直喜欢这样做
result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}[value](x)
https://stackoverflow.com/questions/60208
复制相似问题