119 lines
2.5 KiB
Python
119 lines
2.5 KiB
Python
# Python没有原生的switch-case语句,但可以通过以下几种方式来实现类似的功能:
|
|
|
|
# if-elif-else结构:最直接的方法,适合简单的条件判断
|
|
# 字典映射:推荐的方法,利用字典的键值对映射实现高效的条件分支
|
|
# 函数字典:在字典中存储函数对象,实现复杂的逻辑处理
|
|
# Python 3.10+ match语句:现代Python提供的模式匹配语法
|
|
|
|
|
|
# 字典映射
|
|
def switch_dict(case):
|
|
switcher = {
|
|
"A": "case A",
|
|
"B": "case B",
|
|
"C": "case C",
|
|
}
|
|
return switcher.get(case, "Defaule Case")
|
|
|
|
|
|
result = switch_dict("A")
|
|
print(result) # case A
|
|
result = switch_dict("D")
|
|
print(result) # Defaule Case
|
|
|
|
|
|
# 使用函数字典
|
|
def case_a():
|
|
return "Action for case A"
|
|
|
|
|
|
def case_b():
|
|
return "Action for case B"
|
|
|
|
|
|
def case_c():
|
|
return "Action for case C"
|
|
|
|
|
|
def case_default():
|
|
return "Default action"
|
|
|
|
|
|
def switch_funtion_dice(case):
|
|
switer = {"A": case_a, "B": case_b, "C": case_c}
|
|
fn = switer.get(case, case_default)
|
|
return fn()
|
|
|
|
|
|
result = switch_funtion_dice("A")
|
|
print(result)
|
|
result = switch_funtion_dice("F")
|
|
print(result)
|
|
|
|
|
|
# 自 Python 3.10 起,官方引入了结构化匹配(match 语句),可以原生实现类似 switch 的多分支选择功能。match 让代码更加优雅、可读性更强,尤其适用于分支较多、需要解构或复杂条件匹配的场景。
|
|
|
|
|
|
def switch_match(case):
|
|
"""
|
|
使用 Python 3.10+ 的 match 语句实现 switch 功能
|
|
这是最现代和强大的方法
|
|
"""
|
|
match case:
|
|
case "A":
|
|
return "Case A"
|
|
case "B":
|
|
return "Case B"
|
|
case "C":
|
|
return "Case C"
|
|
case _:
|
|
return "Default case"
|
|
|
|
|
|
result = switch_match("A")
|
|
print(result)
|
|
result = switch_match("F")
|
|
print(result) # Default case
|
|
|
|
|
|
# 数值范围匹配
|
|
def grade_evaluator(sorce):
|
|
grade_map = {
|
|
range(90, 101): "A",
|
|
range(80, 90): "B",
|
|
range(70, 80): "C",
|
|
range(60, 70): "D",
|
|
}
|
|
for score_range, grade in grade_map.items():
|
|
if sorce in score_range:
|
|
return grade
|
|
|
|
return "F"
|
|
|
|
|
|
# 测试成绩评估
|
|
scores = [
|
|
{"scorce": 95},
|
|
{"scorce": 85},
|
|
{"scorce": 75},
|
|
{"scorce": 65},
|
|
{"scorce": 55},
|
|
]
|
|
|
|
for item in scores:
|
|
grade = grade_evaluator(item["scorce"])
|
|
item["grade"] = grade
|
|
|
|
print(scores)
|
|
|
|
|
|
def greet(name, msg="Hello"):
|
|
print(f"{msg}, {name}!")
|
|
|
|
|
|
greet("Alice") # 输出:Hello, Alice!
|
|
greet("Bob", "Hi") # 输出:Hi, Bob!
|
|
|
|
|
|
num_enough = 10
|
|
print(num_enough is False) |