首先Python中并没有Switch/Case语句。那么,该如何实现Switch/Case语句呢?

我们通过一个示例看。将数字1,2,3,4映射为Spring,Summer,Fall,Winter,而其它数字映射为Invalid Season。Java代码中可以用Switch/Case语句来实现:

public static String getSeason(int season) {
   String SeasonName = "";
   switch (season) {
   case 1:
      SeasonName = "Spring";
      break;
   case 2:
      SeasonName = "Summer";
      break;
   case 3:
      SeasonName = "Fall";
      break;
   case 4:
      SeasonName = "Winter";
      break;
   default:
      SeasonName = "Invalid Season";
      break;
   }
   return SeasonName;
}

由于Python中没有SwitchCase语句,所以有两种方式来实现

方法一:if else

def getSeason(season):
    """
    将season映射为字符串
    :param season:
    :return:
    """
    if season == 1:
        return "Spring"
    elif season == 2:
        return "Summer"
    elif season == 3:
        return "Fall"
    elif season == 4:
        return "Winter"
    else:
        return "Invalid Season"

方法二:使用字典(Dict)

可以定义一个字典,然后根据序号来获取相应的字符串

seasondict = {
    1: "Spring",
    2: "Summer",
    3: "Fall",
    4: "Winter"
}

def getSeason(season):
    """
    将season映射为字符串
    :param season:
    :return:
    """
    return seasondict.get(season, "Invalid Season")

如果是要执行方法的话

def Season1():
    return "Spring"
def Season2():
    return "Summer"
def Season3():
    return "Fall"
def Season4():
    return "Winter"
def Default():
    return "Invalid Season"
seasondict = {
    1: Season1,
    2: Season2,
    3: Season3,
    4: Season4
}

def getSeason(season):
    fun = seasondict.get(season, Default)
    return fun()#将这个方法返回并执行

#示例
print(getSeason(2))
#输出
Summer

Q.E.D.