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

在其他语言中,我会使用switch或case语句,但Python似乎没有switch语句。在此场景中,推荐的Python解决方案是什么?


当前回答

除了字典方法(我很喜欢,BTW),您还可以使用if elif else来获得switch/case/default功能:

if x == 'a':
    # Do the thing
elif x == 'b':
    # Do the other thing
if x in 'bc':
    # Fall-through by not using elif, but now the default case includes case 'a'!
elif x in 'xyz':
    # Do yet another thing
else:
    # Do the default

当然,这与switch/case不同——你不可能像放弃break语句那样轻易地通过,但你可以进行更复杂的测试。它的格式比一系列嵌套的if更好,尽管在功能上更接近。

其他回答

Python 3.10(2021)引入了match-case语句,该语句提供了Pythons“switch”的一流实现。例如:

def f(x):
    match x:
        case 'a':
            return 1
        case 'b':
            return 2
        case _:
            return 0   # 0 is the default case if x is not found

match-case语句比这个简单的示例强大得多。


以下原始答案写于2008年,当时还未提供匹配案例:

你可以用字典:

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

如果您真的只是返回一个预定的固定值,那么可以创建一个字典,其中包含所有可能的输入索引作为键,以及它们的对应值。此外,您可能真的不希望函数执行此操作,除非您以某种方式计算返回值。

哦,如果你想做一些类似开关的事情,请看这里。

您可以使用分派的dict:

#!/usr/bin/env python


def case1():
    print("This is case 1")

def case2():
    print("This is case 2")

def case3():
    print("This is case 3")


token_dict = {
    "case1" : case1,
    "case2" : case2,
    "case3" : case3,
}


def main():
    cases = ("case1", "case3", "case2", "case1")
    for case in cases:
        token_dict[case]()


if __name__ == '__main__':
    main()

输出:

This is case 1
This is case 3
This is case 2
This is case 1

扩展“dict as switch”思想。如果要为交换机使用默认值:

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

我要把我的两分钱放在这里。Python中没有case/switch语句的原因是因为Python遵循“只有一种正确的方法”的原则。很明显,您可以想出各种方法来重新创建switch/case功能,但实现这一点的Python方法是if/elf构造。即。,

if something:
    return "first thing"
elif somethingelse:
    return "second thing"
elif yetanotherthing:
    return "third thing"
else:
    return "default thing"

我只是觉得PEP 8应该在这里获得认可。Python的一个优点是它的简单和优雅。这在很大程度上源于PEP8中提出的原则,包括“只有一种正确的方法可以做某事。”