Python Tricks(十九)—— switch 的实现
2016-08-12 11:53
423 查看
python 原生语法不支持 switch,体现了 Python 大道至简的设计思路,有时为了避免啰嗦的
当然我们可以进一步利用 Python 强大的库:
python中switch语句用法
if elif等判断语句,我们可以用字典来代替 switch 的各分支,也即建立表达式和操作的映射。
def add(x, y): return x + y def sub(x, y): return x - y def mul(x, y): return x*y def div(x, y): return float(x)/y def calc(x, o, y): return operators[o](x, y) # 与 operators.get(o)(x, y) 相比会抛出异常 operators = {'+': add, '-': sub, '*': mul, '/': div}
当然我们可以进一步利用 Python 强大的库:
from operator import add, sub, mul, div operators = {'+': add, '-': sub, '*': mul, '/': div}
python中switch语句用法
相关文章推荐
- Python中switch的实现
- [原]python中实现switch
- Python Tricks(八)—— 斐波那契数列的另类实现
- Python Tricks(二十)—— 阶乘的极简实现
- Python实现类似switch的分支结构
- Python中switch的实现
- python 实现case when ,switch的功能
- python 用list,dic实现switch功能的一个奇葩现象
- Tricks(二十三)—— Python 实现树这种数据结构
- Python中实现switch功能
- python中实现switch
- Python的switch实现
- Python利用字典实现switch功能
- python dict 实现 switch 功能
- Python里如何实现C中switch...case的功能
- 设计模式十九(中介者模式,python语言实现)
- 13-python_switch的实现
- python学习笔记(三) 实现switch,内建函数,模块和包
- Python Tricks(十四)—— list 逆序的实现
- Matlab Tricks(十九)—— 序列左右移的实现