我想用 Python 编写一个函数,根据输入索引的值返回不同的固定值。
在其他语言中我会使用switch
or case
声明,但Python似乎没有switch
陈述。这种场景下推荐的Python解决方案有哪些?
Python 3.10 (2021) 引入了match-case https://www.python.org/dev/peps/pep-0634/语句,它为 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
The match
-case
语句比这个简单的例子强大得多。
如果需要支持 Python ≤ 3.9,请改用字典:
def f(x):
return {
'a': 1,
'b': 2,
}[x]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)