对于一个case/switch语句,Python等价于什么?(复制)

时间:2022-10-30 16:13:12

This question already has an answer here:

这个问题已经有了答案:

I'd like to know, is there a Python equivalent for the case statement such as the examples available on VB.net or C#?

我想知道,对于case语句来说,是否存在与Python等价的语句,比如VB.net或c#上的示例?

2 个解决方案

#1


377  

While the official docs are happy not to provide switch, I have seen a solution using dictionaries.

虽然官方文档很乐意不提供交换机,但我看到了使用字典的解决方案。

For example:

例如:

# 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,
}

Then the equivalent switch block is invoked:

然后调用等效开关块:

options[num]()

This begins to fall apart if you heavily depend on fall through.

如果你严重依赖失败,这将开始崩溃。

#2


95  

The direct replacement is if/elif/else.

直接替换为if/elif/else。

However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".

然而,在许多情况下,有更好的方法在Python中实现它。参见“在Python中替换switch语句?”

#1


377  

While the official docs are happy not to provide switch, I have seen a solution using dictionaries.

虽然官方文档很乐意不提供交换机,但我看到了使用字典的解决方案。

For example:

例如:

# 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,
}

Then the equivalent switch block is invoked:

然后调用等效开关块:

options[num]()

This begins to fall apart if you heavily depend on fall through.

如果你严重依赖失败,这将开始崩溃。

#2


95  

The direct replacement is if/elif/else.

直接替换为if/elif/else。

However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".

然而,在许多情况下,有更好的方法在Python中实现它。参见“在Python中替换switch语句?”