寻找elif&if的好替代品,就像开关柜一样
  可能重复: 
  python中switch语句的替代? 
鉴于此方法:
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
我希望以开关盒的形式制作,但是,Python不支持开关盒。
任何替代品?
那么6-len(str(index))呢? 
在这个特定的例子中,我只是使用数学:
def get_index(index):
    return 6 - int(round(math.log(index, 10)))
  你必须使用内置函数round作为math.log返回一个浮点数。 
经典的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()
上一篇: Looking for a good replacement for elif & if , like switch case
下一篇: python if statement too long and ugly, is there a way to shorten it
