Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

python - case / switch语句的Python等价物是什么? [重复](What is the Python equivalent for a case/switch statement? [duplicate])

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#?

(我想知道,是否有一个Python等效的case语句,如VB.net或C#上提供的示例?)

  ask by user1524844 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.
"

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

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

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

# 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.

(如果你严重依赖于跌倒,这就开始分崩离析了。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...