【问题标题】:Looking for a good replacement for elif & if , like switch case [duplicate]寻找 elif 和 if 的良好替代品,例如 switch case [重复]
【发布时间】:2012-12-16 08:24:32
【问题描述】:

可能重复:
Replacements for switch statement in python?

鉴于这种方法:

def getIndex(index):
    if((index) < 10):
        return 5
    elif(index < 100):
        return 4
    elif(index < 1000):
        return 3
    elif(index < 10000):
        return 2
    elif(index < 100000):
        return 1
    elif(index < 1000000):
        return 0

我想把它做成 switch-case 风格,但是 Python 不支持 switch-case 。

有什么替代品吗?

【问题讨论】:

标签: python if-statement switch-statement


【解决方案1】:

6-len(str(index)) 呢?

【讨论】:

    【解决方案2】:

    在这种特殊情况下,我只会使用数学:

    def get_index(index):
        return 6 - int(round(math.log(index, 10)))
    

    您必须使用内置函数round,因为math.log 返回一个浮点数。

    【讨论】:

      【解决方案3】:

      经典的pythonic方法是使用字典,其中键是您的测试,值是反映您打算做什么的可调用函数:

      def do_a():
          print "did a"
      
      self do_b():
          print " did b"
      
      #... etc
      
      opts = {1:do_a, 2:do_b}
      
      if value in opts: 
          opts[value]()
      else:
          do_some_default()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-21
        • 1970-01-01
        • 1970-01-01
        • 2019-02-16
        • 1970-01-01
        • 1970-01-01
        • 2013-09-10
        • 1970-01-01
        相关资源
        最近更新 更多