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來解決某個問題, 並且每種情況下的操作在形式上是相同的(如都執行某個函數並且這些函數有

相同的參數), 就可以用這種方法來實現.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM