Python中Switch Case语法实现
来源:互联网 发布:最好闻的香水知乎 编辑:程序博客网 时间:2024/04/29 06:40
参考文章:http://blog.csdn.net/suiyunonghen/article/details/3734135
python为了追求简洁,没有switch case用法。代替的方式可以用多个if else,最好的就是使用字典方式。
原理:
switch实际上有一个hash表,系统是通过查表来实现跳转的。弄清这个问题之后,转到python的话,你就用dict来实现假定输入in1 执行函数fun1,输入in2 执行函数fun2,输入in3 执行函数fun3,d ata= {‘in1’:fun1,’in2’:fun2,’in3’:fun3}调用的时候就这么写啦,arguments是输入参数d【x】(arguments)
举个栗子:
#定义函数def jia(x,y): print x+ydef jian(x,y): print x-ydef cheng(x,y): print x*ydef chu(x,y): print x/y#字典operator = {'+':jia,'-':jian,'*':cheng,'/':chu}#字典函数-->get方法 返回指定key的值(这里的值是函数)def f(x,o,y): operator.get(o)(x,y)f(3,'+',2)
运行结果:
5Process finished with exit code 0
分析:先定义函数,把函数名作为值放入字典。使用字典的get方法根据输入的key值获取函数(再带入参数计算)
0 0
- Python中Switch Case语法实现
- Python中switch-case实现
- Python中switch-case实现(转)
- python switch…case语法
- Python中Swithch Case语法实现
- Python中Swithch Case语法实现
- Python中Swithch Case语法实现
- Python中Swithch Case语法实现
- python 实现switch/case语句
- switch case 语法
- Python switch/case语句实现方法
- python中没有switch/case语句
- 为什么Python中没有Switch/Case语句?
- Python中为什么没有switch-case
- 为什么Python中没有Switch/Case语句?
- python中实现switch
- haXe语言中改进的switch...case语法
- switch-case 这样的语法
- 基础入门之贪心算法
- 自定义控件的归纳
- RadioButton去掉默认样式小圆点
- Android应用关闭,重启
- 互联网产品灰度发布
- Python中Switch Case语法实现
- Qt浅谈之十三:抓图截屏
- 用setAnimationStyle来设置popwindow显示消失的动画效果
- Android常用控件之ListView(二)
- 农村电商:虽初见成效,但任重道远
- 栈、队列和链表
- Android 读取OTG中配置文件完成自动测试
- WebView内存泄漏记录
- 242. Valid Anagram