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.

In other languages I would use a switch or case statement, but Python does not appear to have a switch statement. What are the recommended Python solutions in this scenario?


你可以使用字典:

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

如果你想使用默认值,你可以使用字典get(key[, default])方法:

def f(x):
    return {
        'a': 1,
        'b': 2
    }.get(x, 9)    # 9 is default if x not found

I've always liked doing it this way

result = {
  'a': lambda x: x * 5,
  'b': lambda x: x + 7,
  'c': lambda x: x - 2
}[value](x)

From here

链接地址: http://www.djcxy.com/p/1136.html

上一篇: Python的隐藏功能

下一篇: 替代Python中的switch语句?