Python中实现多路选择(switch)功能的详细指南

python中实现switch

在 Python 中没有直接的 switch 语句,通常我们用if-elif-else结构或字典映射来实现类似 switch 的功能。

1) 使用 if-elif-else 结构:

def switch(case):
    if case == "A":
        return "Case A"
    elif case == "B":
        return "Case B"
    elif case == "C":
        return "Case C"
    else:
        return "Default case"

result = switch("A")
print(result)  # 输出:"Case A"

2) 使用字典映射(推荐方法):

def switch(case):
    switcher = {
        "A": "Case A",
        "B": "Case B",
        "C": "Case C"
    }
    return switcher.get(case, "Default case")

result = switch("B")
print(result)  # 输出:"Case B"

扩展

当我们使用字典映射时,还可以将字典的值设为函数或lambda 表达式来实现更复杂的逻辑。

def case_a():
    return "Action for case A"

def case_b():
    return "Action for case B"

def case_default():
    return "Default action"

def switch(case):
    switcher = {
        "A": case_a,
        "B": case_b
    }
    func = switcher.get(case, case_default)
    return func()

result = switch("A")
print(result)  # 输出:"Action for case A"

这种方法可以在字典中存储可调用对象(如函数),让我们的 switch 结构更加灵活和强大。

此外,Python 3.10 引入了新的 match 语法,专门用于模式匹配,可以认为是 switch-case 的改进版。示例如下:

def switch(case):
    match case:
        case "A":
            return "Case A"
        case "B":
            return "Case B"
        case "C":
            return "Case C"
        case _:
            return "Default case"

result = switch("C")
print(result)  # 输出:"Case C"

作者:Long韵韵

物联沃分享整理
物联沃-IOTWORD物联网 » Python中实现多路选择(switch)功能的详细指南

发表回复