Python字典替代switch-case

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import re
def one():
    return "one"
def two():
    return "two"
def four():
    return "four"
def three():
    return lambda:"three"

def num2str(args):
    switchers={1:one,2:two,3:lambda:"三",4:four}
    function=switchers.get(args,lambda:"nothing")
    return function()

#去重算法
if __name__ == '__main__':
    print (num2str(3))

运行结果:

PS E:\PyWorkSpace> & C:/Python310/python.exe e:/PyWorkSpace/.vscode/Study.py
三

既可以是用字典去对应方法的值,又可以直接用关键字lambda设置值

你可能感兴趣的:(Python字典替代switch-case)