您的位置:首页 > 编程语言 > Python开发

[Python学习笔记] python中没有swtich

2012-12-11 16:55 363 查看

原地址:http://simonwillison.net/2004/May/7/switch/





Switch statements in Python

Python doesn’t support a native switch statement. I’ve found myself using the following coding idiom instead recently which seems to work pretty well:

{'option1': function1,
'option2': function2,
'option3': function3,
'option4': function4}[value]()
try:
{'option1': function1,
'option2': function2,
'option3': function3,
'option4': function4}[value]()
except KeyError:
# default action
[/code]
This works with lambdas as well, for inline calculations. Here’s a switch statement that assigns to a variable in
PHP:

switch ($value) {
case 'a':
$result = $x * 5;
break;
case 'b':
$result = $x + 7;
break;
case 'c':
$result = $x - 2;
break;
}

And here’s the equivalent code in Python:

result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}[value](x)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: