Python學習(20):字典替代Switch

  • 2020 年 1 月 12 日
  • 筆記

Python本身並不提供Switch的語法功能,為了能夠解決類似switch分支需求的問題,我們可以使用字典代替實現。 解決思路:

  1. 利用字典取值的get方法的容錯性,處理switch語句中的default情況
  2. 設置字典的vlaue為對應方法名,來代替switch語句中的程式碼塊
  3. 為不同key設置相同的value,模擬switch中穿透
def taskForSunday():      print("今天休息")  def taskForRest():      print("今天休息")  def taskForChinese():      print("今天上語文課")  def taskForMath():      print("今天上數學課")  def taskForEnglish():      print("今天上英語課")  def taskForDefault():      print("輸入錯誤啦。。。。")    switchDic = {"Sunday":taskForRest,              "Monday":taskForChinese,              "Tuesday":taskForMath,              "Wednesday":taskForEnglish,              "Tursday":taskForEnglish,              "Friday":taskForEnglish,              "Saturday":taskForRest  }

1.測試取值

通過get獲取字典key對應的方法後,又添加了個括弧,這樣會執行得到的方法

day1 = "Monday"  switchDic.get(day1,taskForDefault)() #列印:今天上語文課

2.測試穿透

##Wednesday,Tursday,Friday三個的效果相同  day2 = "Friday"  switchDic.get(day2,taskForDefault)()  #列印:今天上英語課

3.測試Deault效果

#字典的get方法第二個參數是默認值,即通過key值不能找到value時,返回默認值  #這裡使用了自定義函數的函數名:taskForDefault,用於實現switch的defalut功能  day3 = "天氣不錯哦"  switchDic.get(day3,taskForDefault)() #列印:輸入錯誤啦......