13-python_switch的实现
2013-10-05 16:14
411 查看
python 中的 switch 实现
- python中没有switch关键字
- 定义 字典
- 调用 字典的get(key)获取对应的表达式
def add(x, y) :
return x + y
def subtract(x, y) :
return x - y
def multiply(x, y) :
return x * y
def divide(x, y) :
return x / y
def calculate(x, y, symbol) :
if "+" == symbol :
print add(x, y)
elif "-" == symbol :
print subtract(x, y)
elif "*" == symbol :
print multiply(x, y)
elif "/" == symbol :
print divide(x, y)
else :
pass
calculate(1, 2, "+")
calculate(1, 2, "-")
calculate(1, 2, "*")
calculate(1, 2, "/")
from __future__ import division
def add(x, y) :
return x + y
def subtract(x, y) :
return x - y
def multiply(x, y) :
return x * y
def divide(x, y) :
return x / y
calculateDict = {"+":add, "-":subtract, "*":multiply, "/":divide}
#print calculateDict["+"](1,2)
#print calculateDict.get("+")(1,2)
def calculate(x, y, symbol) :
print calculateDict.get(symbol)(x, y)
calculate(1, 2, "+")
calculate(1, 2, "-")
calculate(1, 2, "*")
calculate(1, 2, "/")
def calculate(x, y, symbol) :
calculateDict = {
"+" : x + y ,
"-" : x - y ,
"*" : x * y ,
"/" : x / y
}
print calculateDict.get(symbol)
calculate(1, 2, "+")
calculate(1, 2, "-")
calculate(1, 2, "*")
calculate(1, 2, "/")
- python中没有switch关键字
- 定义 字典
- 调用 字典的get(key)获取对应的表达式
1. 普通实现
from __future__ import divisiondef add(x, y) :
return x + y
def subtract(x, y) :
return x - y
def multiply(x, y) :
return x * y
def divide(x, y) :
return x / y
def calculate(x, y, symbol) :
if "+" == symbol :
print add(x, y)
elif "-" == symbol :
print subtract(x, y)
elif "*" == symbol :
print multiply(x, y)
elif "/" == symbol :
print divide(x, y)
else :
pass
calculate(1, 2, "+")
calculate(1, 2, "-")
calculate(1, 2, "*")
calculate(1, 2, "/")
2. 字典实现
- value 为 函数from __future__ import division
def add(x, y) :
return x + y
def subtract(x, y) :
return x - y
def multiply(x, y) :
return x * y
def divide(x, y) :
return x / y
calculateDict = {"+":add, "-":subtract, "*":multiply, "/":divide}
#print calculateDict["+"](1,2)
#print calculateDict.get("+")(1,2)
def calculate(x, y, symbol) :
print calculateDict.get(symbol)(x, y)
calculate(1, 2, "+")
calculate(1, 2, "-")
calculate(1, 2, "*")
calculate(1, 2, "/")
3. 常用形式
from __future__ import divisiondef calculate(x, y, symbol) :
calculateDict = {
"+" : x + y ,
"-" : x - y ,
"*" : x * y ,
"/" : x / y
}
print calculateDict.get(symbol)
calculate(1, 2, "+")
calculate(1, 2, "-")
calculate(1, 2, "*")
calculate(1, 2, "/")
相关文章推荐
- Python学习(13)--Lambda表达式和switch语句的实现
- python高效编程技巧13(如何在线程之间实现事件通知)
- python中实现switch,类似表驱动的方式
- 建议13:使用Python模块re实现解析小工具
- Python中实现switch分支结构
- Python中实现switch功能
- python实现switch功能
- Python中实现switch功能实例解析
- Python Tricks(十九)—— switch 的实现
- python学习笔记(三) 实现switch,内建函数,模块和包
- python switch语句的多种实现方法
- python的switch实现
- Python中switch的实现
- python 用list,dic实现switch功能的一个奇葩现象
- Python的switch实现
- python中 switch 语句的实现
- python爬虫日志(13)selenium实现淘宝自动翻页以及在新的标签页中打开网页
- python学习总结---switch功能实现
- Python与人工神经网络(13)——实现卷积神经网络
- python web py入门(13)- 实现发贴到论坛