Python那些优雅的写法:switch-case
生活随笔
收集整理的這篇文章主要介紹了
Python那些优雅的写法:switch-case
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
引言
實際上Python是沒有所謂的switch case寫法的,熟悉C艸和Java的同學可能已經習慣了用switch case結構去優雅的處理一些事情,比如這樣:
switch(變量){ case 變量值1://...;break; case 變量值2://...;break;... case default://...;break; }但是在Python中,官方對switch case的需求是這樣回復的:
" You can do this easily enough with a sequence of if... elif... elif... else. There have been some proposals for switch statement syntax, but there is no consensus (yet) on whether and how to do range tests. "
感覺有點low。
解決
可用字典方法解決這個問題:
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' # switch = {"valueA":functionA,"valueB":functionB,"valueC":functionC} # try: # switch["value"]() #執行相應的方法。 # except KeyError as e: # pass 或 functionX #執行default部分switch = {"a":lambda x:x*2,"b":lambda x:x*3,"c":lambda x:x**x } try:swtich["c"](6) except KeyError as e:pass總結
以上是生活随笔為你收集整理的Python那些优雅的写法:switch-case的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python中 __init__.py的
- 下一篇: python **运算符及多参数传参