python中case的用法_python 中的"switch"用法

转载:http://python.jobbole.com/82008/

为什么Python中没有Switch/Case语句?

不同于我用过的其它编程语言,Python 没有 switch / case 语句。为了实现它,我们可以使用字典映射:

Python

def switch_test_item(item):

switcher = {

"CPU": 0,

"Memory":1,

"BIOSVER":2,

"FAN":3,

"BIOSSETUP":4,

}

return switcher.get(item,"nothing")

这段代码类似于:

function(item){   switch(item){     case “CPU”:       return 0;     case “Memory”:       return 1;

case“BIOSVER”:2:

return:3

……

default:

return “nothing”;   } }

函数的字典映射

在 Python 中字典映射也可以包含函数或者 lambda 表达式:

Python

defzero(): return“zero”   defone(): return“one”   defnumbers_to_functions_to_strings(argument): switcher={ 0:zero, 1:one, 2:lambda:“two”, } # Get the function from switcher dictionary func=switcher.get(argument,lambda:“nothing”) # Execute the function returnfunc()

虽然 zero 和 one 中的代码很简单,但是很多 Python 程序使用这样的字典映射来调度复杂的流程。

example:

def switch_test_item(item, index_b,exename,version,vercheck):

switcher = {

"CPU": CPU_TEST,

"Memory":MEMORY_TEST,

"BIOSVER":BIOSVER_TEST,

"FAN":FAN_TEST,

}

return switcher[item](index_b,exename,version,vercheck)

def CPU_TEST(index_b,exename,version,vercheck):

{

...

}

然后switch_test_item就把index_b,exename,version,vercheck都传递给CPU_TEST等功能函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值