[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)
相关文章推荐
- Python学习笔记(4),字符串没有append用法
- Python学习笔记之疑问 2:python的函数定义为什么没有开始和结束符
- python学习笔记-(5)缩进和分支
- 【转】【Python学习笔记】正则表达式
- 学习python笔记——模块
- python 学习笔记整理
- Python学习笔记——面向对象编程
- Python学习笔记:循环技巧
- python学习笔记-类的descriptor
- Python学习笔记(3)
- python下结巴分词(jieba)学习笔记
- python学习笔记--list基础命令
- python学习笔记(二)
- Python学习笔记--异常处理
- Python学习笔记--2016.08.02
- python2.7 学习笔记 (四)——异常
- Python学习笔记15:Python正则表达式
- Python入门----语句(菜鸟教程的学习笔记)
- python学习笔记3