Looking for a good replacement for elif & if , like switch case

Possible Duplicate:
Replacements for switch statement in python?

Given this method :

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

I want to make it in a switch-case style , however , Python doesn't support switch case .

Any replacements for that ?


那么6-len(str(index))呢?


In this particular instance I would just use maths:

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

You have to use the built-in function round as math.log returns a float.


经典的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()
链接地址: http://www.djcxy.com/p/42758.html

上一篇: 如何在python中实现switch case??

下一篇: 寻找elif&if的好替代品,就像开关柜一样