99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀你們都有switch,憑什么我python沒有?
你們都有switch,憑什么我python沒有?
2022-04-02
收藏

作者:麥?zhǔn)?

來源:麥?zhǔn)寰幊?

?

學(xué)過其他編程語言的同學(xué)肯定發(fā)現(xiàn)了我們Python語言中竟然沒有"很常見"的switch/case關(guān)鍵字,更別提對應(yīng)的語法結(jié)構(gòu)了。既然沒有,有些時候又需要用,那只能自己寫一個"fake_switch"了。

?

你們都有switch,憑什么我<a href='/map/python/' style='color:#000;font-size:inherit;'>python</a>沒有?

以Java的switch用法進行參照(摘自菜鳥教程)

public class Test { public static void main(String args[]){ char grade = 'C'; switch(grade)
      { case 'A' :
            System.out.println("優(yōu)秀"); break; case 'B' : case 'C' :
            System.out.println("良好"); break; case 'D' :
            System.out.println("及格"); break; case 'F' :
            System.out.println("你需要再努力努力"); break; default :
            System.out.println("未知等級");
      }
      System.out.println("你的等級是 " + grade);
   }
}

用if-elif-else代替

def fake_switch_1(grade:str) -> str: if grade == "A": return "優(yōu)秀" elif grade == "B" or grade == "C": return "良好" elif grade == "D": return "及格" elif grade == "F": return "你需要再努力努力" else: return "未知等級" # 調(diào)用顯示結(jié)果 print(fake_switch_1("A"))
print(fake_switch_1("B"))
print(fake_switch_1("C"))
print(fake_switch_1("D"))
print(fake_switch_1("F"))
print(fake_switch_1("Z"))

運行代碼:

優(yōu)秀
良好
良好
及格
你需要再努力努力
未知等級

用字典(dict)+ try...except...語句代替

def fake_swith_2(grade:str) -> str: level = { "A":"優(yōu)秀", "B":"良好", "C":"良好", "D":"及格", "F":"你需要再努力努力", 
   } try:
       g = level[grade] except Exception:
       g = "未知等級" return g # 調(diào)用顯示結(jié)果  print(fake_switch_2("A"))
print(fake_switch_2("B"))
print(fake_switch_2("C"))
print(fake_switch_2("D"))
print(fake_switch_2("F"))
print(fake_switch_2("Z"))

運行代碼:

優(yōu)秀
良好
良好
及格
你需要再努力努力
未知等級

match...case...語句(Python3.10以后引入)

這個算是屬于python自己的switch/case語句了,其用法基本和其他語言的switch/case語句一樣。

def fake_switch_3(grade:str) -> str:
    match grade: case "A": return "優(yōu)秀" case "B": return "良好" case "C": return "良好" case "D": return "及格" case "F": return "你需要再努力努力" case _: return "未知等級" print(fake_switch_3("A")) print(fake_switch_3("B")) print(fake_switch_3("C")) print(fake_switch_3("D")) print(fake_switch_3("F")) print(fake_switch_3("Z"))

運行代碼:

優(yōu)秀
良好
良好
及格
你需要再努力努力
未知等級

?

最后一段的case _:類似于 C 和 Java 中的default:,當(dāng)匹配不到字符時就會執(zhí)行該語句下的表達式。

?

總結(jié)

我自己感覺用Python字典(dict)+ try...except...的形式去實現(xiàn)switch/case的功能會讓代碼顯得更整潔更pythonic。在維護這段代碼時只要注重字典(dict)中的鍵值對和try語句中defult的值,而不用太去關(guān)注邏輯判斷上是否會出問題,在某種意義上講,這可能還是超越switch/case的地方。

「小伙伴們,這三種選擇結(jié)構(gòu),你們喜歡哪種呢?請在評論區(qū)留言,加上喜歡的原因,那就更好了?!?/span>

關(guān)于python為什么沒有switch/case語句

你們都有switch,憑什么我<a href='/map/python/' style='color:#000;font-size:inherit;'>python</a>沒有?

根據(jù)上圖表面,前期Python之父Guido是不希望引入switch/case規(guī)則的,他曾說“Python is fine without a switch statement”。但十五年后,Guido卻引入了match/case規(guī)則,難道m(xù)atch/case逃不出真香定律?

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }