zoukankan      html  css  js  c++  java
  • python技巧 switch case语句

    不同于C语言和SHELL,python中没有switch case语句,关于为什么没有,官方的解释是这样的

    使用Python模拟实现的方法:

    def switch_if(fun, x, y):
        if fun == 'add':
            return x + y
        elif fun == 'sub':
            return x - y
        elif fun == 'mul':
            return x * y
        elif fun == 'div':
            return x / y
        else:
            return None


    def switch_dict(fun, x, y):
        return {
            'add': lambda: x + y,
            'sub': lambda: x - y,
            'mul': lambda: x * y,
            'div': lambda: x / y,
        }.get(fun,None)()


    print("switch_if('add',1,2):",switch_if('add',1,2))
    print("switch_if('sub',1,2):",switch_if('sub',1,2))
    print("switch_if('mul',1,2):",switch_if('mul',1,2))
    print("switch_if('div',1,2):",switch_if('div',1,2))

    print("switch_dict('add',1,2):",switch_dict('add',1,2))
    print("switch_dict('sub',1,2):",switch_dict('sub',1,2))
    print("switch_dict('mul',1,2):",switch_dict('mul',1,2))
    print("switch_dict('div',1,2):",switch_dict('div',1,2))

    switch_if('add',1,2): 3
    switch_if('sub',1,2): -1
    switch_if('mul',1,2): 2
    switch_if('div',1,2): 0.5
    switch_dict('add',1,2): 3
    switch_dict('sub',1,2): -1
    switch_dict('mul',1,2): 2
    switch_dict('div',1,2): 0.5

  • 相关阅读:
    ulimit c unlimited
    2021.9.28 Sqoop
    2021.9.30 利用sqoop将hive数据导出到mysql
    2021.10.2 建造者模式
    111每日博客
    1029每日博客
    112每日博客
    113每日博客
    Panda 交易所视点观察!区块链金融应用迎新规,哪些版块受影响?
    c# 读取word
  • 原文地址:https://www.cnblogs.com/flashBoxer/p/9990627.html
Copyright © 2011-2022 走看看