美文网首页
Python字典替代switch-case

Python字典替代switch-case

作者: 清明捉鬼 | 来源:发表于2022-09-23 18:07 被阅读0次
    #!/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

          本文链接:https://www.haomeiwen.com/subject/hjvnortx.html