python语言中,没有内置switch函数,如果用if-else语句的话,当分支数量很大时,会显得很臃肿,下面是使用python中的字典,实现switch语句功能的方法。
# 设置flag的值,用于选择执行哪个函数
flag = 0
# 设置自定义函数
def get_function_1():
# 函数功能
return 'Function_1'
def get_function_2():
# 函数功能
return 'Function_2'
def get_function_3():
# 函数功能
return 'Function_3'
def get_default():
# 函数功能
return 'Others'
# 字典中不同的值对应不同的自定义函数
switcher = {
0: get_function_1,
1: get_function_2,
2: get_function_3
}
# 根据flag的值决定执行哪一个函数,如果输入的值在字典中没有,则执行get_default函数
output = switcher.get(flag, get_default)()
print("The output of switcher is: ", output)
如果语句不复杂,也可以使用lambda表达式,可以使代码更简洁,lambda表达式介绍见Python lambda介绍 - Goodpy - 博客园www.cnblogs.com
下面是利用了字典和lambda表达式,实现switch语句功能
flag = 0
# 如果字典中没有flag的值,则执行get_default函数
def get_default(x):
# 函数功能
return 'None'
switcher = {
0: lambda x:x+1,
1: lambda x:x**2,
2: lambda x:abs(x)
}
output = switcher.get(flag, get_default)(5)
print("The output of switcher is: ", output)