扫码关注官方订阅号
Python里怎么实现switch case?
闭关修行中......
Python 里没有 Switch 语法,按官方的说法是用 if...elif... 来替代 switch...case
if...elif...
switch...case
An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages.
但是可以用 Dictionary 来实现:
def f(x): return { 'a': 1, 'b': 2, }[x]
参考:http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python
用if或者 字典 实现应该都没有问题吧。http://stackoverflow.com/questions/11479816/what-is-the-python-equivalent-for-a-case-switch-statement
if
楼主可以参考一下这个http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python
python没有switch case。switch case从逻辑上来说像是一个hash表。你可以使用python的字典来实现类似功能。
switch_dict = { "case_foo": foo(), "case_bar": bar(), ... } switch_dict.get("case", "default_case")()
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
Python 里没有 Switch 语法,按官方的说法是用
if...elif...来替代switch...case但是可以用 Dictionary 来实现:
参考:http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python
用
if或者 字典 实现应该都没有问题吧。http://stackoverflow.com/questions/11479816/what-is-the-python-equivalent-for-a-case-switch-statement
楼主可以参考一下这个
http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python
python没有switch case。switch case从逻辑上来说像是一个hash表。你可以使用python的字典来实现类似功能。