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
-------------------------
['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
-------------------------
['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
-------------------------
['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
-------------------------
['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
-------------------------
['1', '(', '9']
-------------------------
PS J:\>

   个人感觉, 如果想用switch来解决某个问题, 并且每种情况下的操作在形式上是相同的(如都执行某个函数并且这些函数有

相同的参数), 就可以用这种方法来实现.

转载于:https://www.cnblogs.com/lxw0109/p/Python-funcName-DictValue.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值