Python 函数名作为字典值,, Python中是
Python 函数名作为字典值,, 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/05import redef add(x, y): return x + ydef sub(x, y): return x - ydef mul(x, y): return x * ydef div(x, y): return x / ydef 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: passif __name__ == ‘__main__‘: main()
Output:
PS J:\> python .\switchDict.pyPlease input the easy expression:(e.g. 1 + 2.But 1 + 2 + 3 are not accepted.1 + 2-------------------------[‘1‘, ‘+‘, ‘2‘]-------------------------33PS J:\> python .\switchDict.pyPlease input the easy expression:(e.g. 1 + 2.But 1 + 2 + 3 are not accepted.4 - 9-------------------------[‘4‘, ‘-‘, ‘9‘]--------------------------5-5PS J:\> python .\switchDict.pyPlease input the easy expression:(e.g. 1 + 2.But 1 + 2 + 3 are not accepted.6 / 5-------------------------[‘6‘, ‘/‘, ‘5‘]-------------------------11PS J:\> python .\switchDict.pyPlease input the easy expression:(e.g. 1 + 2.But 1 + 2 + 3 are not accepted.1 9 9-------------------------[‘1‘, ‘‘, ‘9‘, ‘ ‘, ‘9‘]-------------------------PS J:\> python .\switchDict.pyPlease input the easy expression:(e.g. 1 + 2.But 1 + 2 + 3 are not accepted.1 ( 9-------------------------[‘1‘, ‘(‘, ‘9‘]-------------------------PS J:\>
个人感觉, 如果想用switch来解决某个问题, 并且每种情况下的操作在形式上是相同的(如都执行某个函数并且这些函数有
相同的参数), 就可以用这种方法来实现.
Python 函数名作为字典值
相关内容
- python的垃圾回收机制,,python垃圾回收
- python实现冒泡排序,,代码#!/usr/b
- Python 字符串title()、upper()、lower()方法,,1. 概述在Pyth
- python3 字典,,字典是另一种可变容器
- Python3正则表达式清洗Excel文档,,本项目中虽然数据量不
- python进阶一(函数式编程)【2-6 python中闭包】,,pyth
- Python标准库12 数学与随机数 (math包,random包),,作者:
- PYTHON 写函数,检查用户传入的对象(字符串、列表、元
- numpy ndarray 杩斿洖 index 闂,,鏍囩锛?a hre
- 矩阵的运算:Python语言实现,,一.矩阵的加减法im
评论关闭