Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - 在Python中替换switch语句?(Replacements for switch statement in Python?)

I want to write a function in Python that returns different fixed values based on the value of an input index.

(我想用Python编写一个函数,该函数根据输入索引的值返回不同的固定值。)

In other languages I would use a switch or case statement, but Python does not appear to have a switch statement.

(在其他语言中,我将使用switchcase语句,但是Python似乎没有switch语句。)

What are the recommended Python solutions in this scenario?

(在这种情况下,推荐的Python解决方案是什么?)

  ask by Michael Schneider translate from so

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

1 Reply

0 votes
by (71.8m points)

You could use a dictionary:

(您可以使用字典:)

def f(x):
    return {
        'a': 1,
        'b': 2,
    }[x]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...