zoukankan      html  css  js  c++  java
  • Python中使用字典完成switch功能

    概述:

      在某些场景下,swith 比 if else 的效率更高,但是在 Python 中是没有switch的,今天学到了一种用字典实现switch功能的方法

    案例:

      Python 2下,实现都2个计算器功能,就是简单的加减乘除

    首先使用 if else的方式

    #/usr/bin/python
    #coding:utf-8
    
    from __future__ import division
    
    def jia(x,y):
        return x+y
    
    def jian(x,y):
        return x-y
    
    def cheng(x,y):
        return x*y
    
    def chu(x,y):
        return x/y
    
    def operator(x,o,y):
        if o == "+":
            print jia(x,y)
        elif o == '-':
            print jian(x,y)
        elif o == '*':
            print cheng(x,y)
        elif o == '/':
            print chu(x,y)
        else:
            pass
    
    operator(2,'+',4)
    operator(2,'-',4)
    operator(2,'*',4)
    operator(2,'/',4)

    从代码中可以看出,如果要执行除法,或者四则运算以外的计算,需要把之前的if条件都要判断一遍,效率不高。可以尝试使用字典来改写

    #/usr/bin/python
    #coding:utf-8
    
    from __future__ import division
    
    def jia(x,y):
        return x+y
    
    def jian(x,y):
        return x-y
    
    def cheng(x,y):
        return x*y
    
    def chu(x,y):
        return x/y
    
    ##用字典实现switch
    operator={"+":jia,"-":jian,"*":cheng,"/":chu}
    
    print operator["+"](3,2)
    print operator["/"](3,2)
     
     ##用 get ,对没有的运算符不会报KeyError
    print operator.get("%")(3,2)
    
    def f(x,o,y):
        print operator.get(o)(x,y)



    '''
    通过字典调用函数格式如下
    {1:case1,2:case2}.get(x,lambda *arg,**kwargs:)()

    '''

    ##代码可以继续简化,直接在字典中进行运算

    #/usr/bin/python
    #coding:utf-8

    from __future__ import division
    x=1
    y=2
    operator="/"
    result={"+":x+y,"-":x-y,"*":x*y,"/":x/y}
    print result.get(operator)

    案例比较简单,主要是学习思路

  • 相关阅读:
    Nodejs Express4.x学习笔记
    OSG学习 错误与心得
    Qt Visual Studio Add-in安装
    OSG安装配置
    钩子
    不要去追一匹马,用追马的时间种草
    intellij Idea 报jdk错误
    flex 安全沙箱问题
    webuploader
    文件上传下载
  • 原文地址:https://www.cnblogs.com/bxhsdy/p/13254481.html
Copyright © 2011-2022 走看看