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

熱線(xiàn)電話(huà):13121318867

登錄
首頁(yè)精彩閱讀你們都有switch,憑什么我python沒(méi)有?
你們都有switch,憑什么我python沒(méi)有?
2022-04-02
收藏

作者:麥?zhǔn)?

來(lái)源:麥?zhǔn)寰幊?

?

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

?

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

以Java的switch用法進(jìn)行參照(摘自菜鳥(niǎo)教程)

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("未知等級(jí)");
      }
      System.out.println("你的等級(jí)是 " + 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 "未知等級(jí)" # 調(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ùn)行代碼:

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

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

def fake_swith_2(grade:str) -> str: level = { "A":"優(yōu)秀", "B":"良好", "C":"良好", "D":"及格", "F":"你需要再努力努力", 
   } try:
       g = level[grade] except Exception:
       g = "未知等級(jí)" 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ùn)行代碼:

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

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

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

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 "未知等級(jí)" 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ùn)行代碼:

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

?

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

?

總結(jié)

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

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

關(guān)于python為什么沒(méi)有switch/case語(yǔ)句

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

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

數(shù)據(jù)分析咨詢(xún)請(qǐng)掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

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

OK
客服在線(xiàn)
立即咨詢(xún)
客服在線(xiàn)
立即咨詢(xún)
') } 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(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶(hù)后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說(shuō)明請(qǐng)參見(jiàn):http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".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 = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+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); }