Python里怎么实现switch case?
阿神
阿神 2017-04-17 13:51:33
[Python讨论组]

Python里怎么实现switch case?

阿神
阿神

闭关修行中......

全部回复(4)
怪我咯

Python 里没有 Switch 语法,按官方的说法是用 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

PHP中文网

楼主可以参考一下这个
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")()
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号