Python---如何用字典映射代替switch case语句

switch (day)
{case 0:
     dayName='sunday';
     break;
 case 1:
     dayName='monday';
     break;
 case 2:
     dayName='tuesday';
     break;
 default:
     dayName='unkown';
     break;
 }

    
"""
 字典映射   
"""
day=0
switcher={0:'sunday',1:'monday',2:'tuesday'}
day_name=switcher[day]
print(day_name)#sunday

day=6
switcher={0:'sunday',1:'monday',2:'tuesday'}
day_name=switcher[day]
print(day_name)#报错
#处理方法
day=6
switcher={0:'sunday',1:'monday',2:'tuesday'}
day_name=switcher.get(day,'unkown')
print(day_name)#unkown

"""
有函数的情况
"""
day=1
def get_sunday():
    return 'sunday'
def get_monday():
    return 'monday'
def get_tuesday():
    return 'tuesday'
def get_default():
    return 'unkown'
switcher={0:get_sunday,1:get_monday,2:get_tuesday}
day_name=switcher.get(day,get_default)()
print(day_name)#monday

day=6
def get_sunday():
    return 'sunday'
def get_monday():
    return 'monday'
def get_tuesday():
    return 'tuesday'
def get_default():
    return 'unkown'
switcher={0:get_sunday,1:get_monday,2:get_tuesday}
day_name=switcher.get(day,get_default)()
print(day_name)#unkown

 

你可能感兴趣的:(Python---如何用字典映射代替switch case语句)