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

我想知道,是否有一个与案例语句相当的Python,例如VB.net或C#上的示例?

虽然官方文档很乐意不提供切换,但我已经看到了使用字典的解决scheme 。

例如:

# 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]() 

如果你严重依赖于跌倒,这将开始崩溃。

直接replace是if / elif / else

但是,在很多情况下,有更好的方法在Python中完成。 请参阅“ replacePython中的switch语句? ”。

Interesting Posts