case / switch语句的Python等价物是什么?

时间:2012-07-14 00:01:59

标签: python switch-statement case-statement

我想知道,是否有案例声明的Python等效项,例如VB.net或C#上提供的示例?

2 个答案:

答案 0 :(得分:469)

虽然official docs很高兴不提供切换功能,但我看到了solution using dictionaries

例如:

# define the function blocks
def zero():
    print "You typed zero.\n"

def sqr():
    print "n is a perfect square\n"

def even():
    print "n is an even number\n"

def prime():
    print "n is a prime number\n"

# map the inputs to the function blocks
options = {0 : zero,
           1 : sqr,
           4 : sqr,
           9 : sqr,
           2 : even,
           3 : prime,
           5 : prime,
           7 : prime,
}

然后调用等效的开关块:

options[num]()

如果你严重依赖摔倒,这就会开始分崩离析。

答案 1 :(得分:133)

直接替换为if / elif / else

但是,在许多情况下,有更好的方法在Python中执行此操作。请参阅“Replacements for switch statement in Python?”。

相关问题