Python 函数名作为字典值
Python中是没有switch的, 所以有时我们需要用switch的用法, 就只能通过if else来实现了. 但if else写起来比较冗长,
这时就可以使用Python中的dict来实现, 比switch还要简洁. 用法如下:
如果是key1的情况就执行func1, 如果是key2的情况就执行func2...(func1, func2...所有的函数的参数形式需要相同),
假设各个函数参数均为(arg1, arg2):
dictName = {"key1":func1, "key2":func2, "key3":func3"...} #字典的值直接是函数的名字,不能加引号
dictName[key](arg1, arg2)
示例代码如下:
#!/usr/bin/python
#File: switchDict.py
#Author: lxw
#Time: 2014/10/05 import re 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 x / y def main():
inStr = raw_input("Please input the easy expression:(e.g. 1 + 2.But 1 + 2 + 3 are not accepted.\n")
inList = re.split("(\W+)", inStr)
inList[1] = inList[1].strip()
print("-------------------------")
print(inList)
print("-------------------------") #Method 1:
if inList[1] == "+":
print(add(int(inList[0]), int(inList[2])))
elif inList[1] == "-":
print(sub(int(inList[0]), int(inList[2])))
elif inList[1] == "*":
print(mul(int(inList[0]), int(inList[2])))
elif inList[1] == "/":
print(div(int(inList[0]), int(inList[2])))
else:
pass #Method 2:
try:
operator = {"+":add, "-":sub, "*":mul, "/":div}
print(operator[inList[1]](int(inList[0]), int(inList[2])))
except KeyError:
pass if __name__ == '__main__':
main()
Output:
PS J:\> python .\switchDict.py
Please input the easy expression:(e.g. 1 + 2.But 1 + 2 + 3 are not accepted.
1 + 2
-------------------------
['', '+', '']
-------------------------
3
3
PS J:\> python .\switchDict.py
Please input the easy expression:(e.g. 1 + 2.But 1 + 2 + 3 are not accepted.
4 - 9
-------------------------
['', '-', '']
-------------------------
-5
-5
PS J:\> python .\switchDict.py
Please input the easy expression:(e.g. 1 + 2.But 1 + 2 + 3 are not accepted.
6 / 5
-------------------------
['', '/', '']
-------------------------
1
1
PS J:\> python .\switchDict.py
Please input the easy expression:(e.g. 1 + 2.But 1 + 2 + 3 are not accepted.
1 9 9
-------------------------
['', '', '', ' ', '']
-------------------------
PS J:\> python .\switchDict.py
Please input the easy expression:(e.g. 1 + 2.But 1 + 2 + 3 are not accepted.
1 ( 9
-------------------------
['', '(', '']
-------------------------
PS J:\>
个人感觉, 如果想用switch来解决某个问题, 并且每种情况下的操作在形式上是相同的(如都执行某个函数并且这些函数有
相同的参数), 就可以用这种方法来实现.
Python 函数名作为字典值的更多相关文章
- python函数2(返回值、传递列表...)
python函数2(返回值.传递列表...) 1.返回值 1.1.返回简单的值 #返回简单值 def get_formatted_name(first_name,last_name): "& ...
- 9 - Python函数定义-位置参数-返回值
目录 1 函数介绍 1.1 为什么要使用函数 1.2 Python中的函数 2 函数的基本使用 3 函数的参数 3.1 参数的默认值 3.2 可变参数 3.2.1 可变位置传参 3.2.2 可变关键字 ...
- python函数基础-参数-返回值-注释-01
什么是函数 函数就是有特定功能的工具 # python中有内置函数(python解释器预先封装好的)与自定义函数(用户自定义封装的)之分 为什么要用函数 # 可以减少代码冗余,增加代码复用性 # 使代 ...
- Python函数变量和返回值
Python函数的全局变量和局部变量 1.不同的编程语言,程序可以分为函数和过程两大类,函数具有具体返回值,而过程则不具有具体的返回值,python只具有函数,因为对于它的一般函数,其返回值为所具体返 ...
- python函数1_参数,返回值和嵌套
函数 将重复的代码,封装到函数,只要使用直接找函数 函数可以增强代码的模块化和提高代码的重复利用率 函数的定义和调用 格式 def 函数名([参数,参数...]): 函数体 定义函数 import r ...
- Python函数(一)-return返回值
定义一个函数可以在最后加上return返回值,方便查看函数是否运行完成和返回函数的值 # -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR&qu ...
- python 函数返回多个值
参考文献:http://blog.csdn.net/facevoid/article/details/5369146
- python函数,定义,参数,返回值
python中可以将某些具备一定功能的代码写成一个函数,通过函数可以在一定程度上减少代码的冗余,节约书写代码的时间.因为有一些代码实现的功能我们可能会在很多地方用到. 1.函数的声明与定义 通过def ...
- Python函数参数默认值的陷阱和原理深究"
本文将介绍使用mutable对象作为Python函数参数默认值潜在的危害,以及其实现原理和设计目的 本博客已经迁移至: http://cenalulu.github.io/ 本篇博文已经迁移,阅读全文 ...
随机推荐
- DMA摘记
1.特点 PIO模式下硬盘和内存之间的数据传输是由CPU来控制的:而在DMA模式下,CPU只须向DMA控制器下达指令,让DMA控制器来处理数据的传送,数据传送完毕再把信息反馈给CPU,这样就很大程度上 ...
- ltp的使用
ltp 可以分词 词性识别 命名实体识别,使用过程: import pyltp from pyltp import SentenceSplitter from pyltp import Segment ...
- 【原创】菜鸟版Android 笔记2- Activity
1. Activity介绍 Acitivity在安卓开发中非常重要,他很像Java桌面开发中的JFrame,在MVC模式中属于Controller,一般一个应用程序通常由多个松耦合关系的activit ...
- 工业控制系统PLC、DCS、ESD
PLC:可编程逻辑控制系统.PLC是一种专为在工业环境应用而设计的数字运算电子系统. DCS:集散控制系统. ESD:紧急停车系统.
- uva753 A Plug for UNIX 网络流最大流
C - A Plug for UNIX You are in charge of setting up the press room for the inaugural meeting of t ...
- 12:Web及MySQL服务异常监测案例
[root@db01 scripts]# cat db_check.sh #!/bin/bash db_num=$(mysql -h172. -P3306 -uroot -poldboy123 -e ...
- Snowflake Snow Snowflakes - poj 3349 (hash函数)
判断n朵雪花中,是否有完全一样的雪花.简单的hash,将雪花的六个边的权值加起来,记为sum,将sum相等的雪花归为一类,再在这里面根据题意找完全相同的,判断顺时针或者逆时针的所有角是否一模一样. # ...
- Starting Tomcat v7.0 Server at localhost' has encountered a problem. 如何解决
刚刚学习JavaWeb,遇到了一个问题 因为是初学,我在工程中编写了一个JSP,想要在浏览器中打开,然后出现了这个问题: 在途中大家可以看到,我点击运行写好的JSP,却出现错误,真正的原因是因为Jav ...
- python 集合set remove update add
1. 集合(set):把不同的元素组成一起形成集合,是python基本的数据类型. 集合对象是一组无序排列hashable value:集合成员可以做字典的键. 集合就像是 list 和 dict 的 ...
- cocos2dx-3.0(前言)
说了好久,告诉自己要開始学cocos2dx(在心理里告诉了好久),然后养成良好习惯,记录自己学习cocos2dx的过程.一个是怕自己忘记.还有一个是更加让自己理解透彻(或许哪天我写的好了,组合一下出一 ...