【问题标题】:python - Simulating 'else' in dictionary switch statementspython - 在字典 switch 语句中模拟“else”
【发布时间】:2013-03-08 23:52:06
【问题描述】:

我正在处理一个使用 If, Elif, Elif, ...Else 结构负载的项目,后来我将其更改为类似 switch 的语句,如 herehere 所示。

我将如何在If, Elif, Else 语句中添加类似于 Else 的一般“嘿,该选项不存在”案例 - 如果没有 Ifs 或 Elifs 则执行跑起来?

【问题讨论】:

    标签: python switch-statement case if-statement


    【解决方案1】:

    如果else真的不是异常情况,get的时候使用可选参数不是更好吗?

    >>> choices = {1:'one', 2:'two'}
    >>> print choices.get(n, 'too big!')
    
    >>> n = 1
    >>> print choices.get(n, 'too big!')
    one
    
    >>> n = 5
    >>> print choices.get(n, 'too big!')
    too big!
    

    【讨论】:

      【解决方案2】:

      您可以捕获在映射中找不到值时出现的KeyError 错误,并在那里返回或处理默认值。比如用n = 3这段代码:

      if n == 1:
          print 'one'
      elif n == 2:
          print 'two'
      else:
          print 'too big!'
      

      变成这样:

      choices = {1:'one', 2:'two'}
      try:
          print choices[n]
      except KeyError:
          print 'too big!'
      

      无论哪种方式,'too big!' 都会打印在控制台上。

      【讨论】:

      • 啊,这么简单,我怎么一开始没看到呢!无论如何,谢谢,我相信其他人也可以从中获得一些帮助:P
      • 哦,当然。让我先试一试——我只是一个男人! :P
      【解决方案3】:

      您链接到的first article 有一个非常干净的解决方案:

      response_map = {
          "this": do_this_with,
          "that": do_that_with,
          "huh": duh
      }
      response_map.get( response, prevent_horrible_crash )( data )
      

      如果response 不是response_map 中列出的三个选项之一,这将调用prevent_horrible_crash

      【讨论】:

        【解决方案4】:

        假设您有一个函数 f(a,b) 并根据某个变量 x 的值设置不同的参数。因此,如果 x='Monday' 并且如果 x='Saturday' 您希望使用 a=5 和 b=9 执行 f,则您希望使用 a=1 和 b=3 执行 f。否则,您将打印不支持这样的 x 值。

        我愿意

        from functools import partial
        def f(a,b):
         print("A is %s and B is %s" % (a,b))
        
        def main(x):
         switcher = {
                     "Monday": partial(f,a=1, b=3),
                     "Saturday": partial(f, a=5, b=9)
                    }
         if x not in switcher.keys():
          print("X value not supported")
          return
        
         switcher[x]()
        

        这样 f 不是在声明切换器时执行,而是在最后一行执行。

        【讨论】:

          【解决方案5】:

          一些单行替代方案:

          choices = {1:'one', 2:'two'}
          key = 3
          
          # returns the provided default value if the key is not in the dictionary
          print(choices[key] if key in choices else 'default_value')
          
          # or using the dictionary get() method
          print(choices.get(key, 'default_value')
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多