本文目錄一覽:
python中有switch語句嗎
python官網的回答(地址:):
You can do this easily enough with a sequence of if… elif… elif… else.
意思就是:python語法講究簡單明了,if else完全可以很簡單的實現switch的所有功能,沒必要用switch。
為什麼Python中沒有Switch/Case語句
因為作為一門解釋型語言,switch/case是沒有存在必要的,if/elif/else就可以實現的功能,為什麼要再提供重複的?
if else的得一個if一個if的判斷過去,如果匹配的是最後一個條件,前面所有if都得判斷一遍的。
看過彙編就知道,C語言的switch/case,在case值連續的時候,是可以根據case值直接計算該跳轉的地址的。
Python里怎麼實現switch case
學習Python過程中,發現沒有switch-case,過去寫C習慣用Switch/Case語句,官方文檔說通過if-elif實現。所以不妨自己來實現Switch/Case功能。
方法一
通過字典實現
def foo(var):
return {
‘a’: 1,
‘b’: 2,
‘c’: 3,
}.get(var,’error’) #’error’為默認返回值,可自設置
方法二
通過匿名函數實現
def foo(var,x):
return {
‘a’: lambda x: x+1,
‘b’: lambda x: x+2,
‘c’: lambda x: x+3,
}[var](x)
方法三
通過定義類實現
參考Brian Beck通過類來實現Swich-case
# This class provides the functionality we want. You only need to look at
# this if you want to know how this works. It only needs to be defined
# once, no need to muck around with its internals.
class switch(object):
def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
“””Return the match method once, then stop”””
yield self.match
raise StopIteration
def match(self, *args):
“””Indicate whether or not to enter a case suite”””
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False
# The following example is pretty much the exact use-case of a dictionary,
# but is included for its simplicity. Note that you can include statements
# in each suite.
v = ‘ten’
for case in switch(v):
if case(‘one’):
print 1
break
if case(‘two’):
print 2
break
if case(‘ten’):
print 10
break
if case(‘eleven’):
print 11
break
if case(): # default, could also just omit condition or ‘if True’
print “something else!”
# No need to break here, it’ll stop anyway
# break is used here to look as much like the real thing as possible, but
# elif is generally just as good and more concise.
# Empty suites are considered syntax errors, so intentional fall-throughs
# should contain ‘pass’
c = ‘z’
for case in switch(c):
if case(‘a’): pass # only necessary if the rest of the suite is empty
if case(‘b’): pass
# …
if case(‘y’): pass
if case(‘z’):
print “c is lowercase!”
break
if case(‘A’): pass
# …
if case(‘Z’):
print “c is uppercase!”
break
if case(): # default
print “I dunno what c was!”
# As suggested by Pierre Quentel, you can even expand upon the
# functionality of the classic ‘case’ statement by matching multiple
# cases in a single shot. This greatly benefits operations such as the
# uppercase/lowercase example above:
import string
c = ‘A’
for case in switch(c):
if case(*string.lowercase): # note the * for unpacking as arguments
print “c is lowercase!”
break
if case(*string.uppercase):
print “c is uppercase!”
break
if case(‘!’, ‘?’, ‘.’): # normal argument passing style also applies
print “c is a sentence terminator!”
break
if case(): # default
print “I dunno what c was!”
# Since Pierre’s suggestion is backward-compatible with the original recipe,
# I have made the necessary modification to allow for the above usage.
查看Python官方:PEP 3103-A Switch/Case Statement
發現其實實現Switch Case需要被判斷的變數是可哈希的和可比較的,這與Python倡導的靈活性有衝突。在實現上,優化不好做,可能到最後最差的情況彙編出來跟If Else組是一樣的。所以Python沒有支持。
如何理解 python中的switch
方法/步驟
1
我們以加減和一個隨意名字的函數來解析switch的用法,說白了也是很簡答嗎的。首先添加一個add的方法。
2
再添加一個相減的方法,同時加了print方便debug程序。
3
之後為了作對比,隨便寫了一個abc的方法。
4
建立一個字典,用『+』,『-』,『abc』分別作為key,對應相映的方法。
5
之後再加兩個方法,通過對於參數的調整,用字典的get『key』方法獲取函數,並且傳入參數。
6
試著用(1,『+』,5) 來實現1+5。
7
用(6,『-』,2) 來實現6-2,調用的都是同一個方法,參數不同,通過字典key獲取到的函數也不同,這就是我所理解的switch的用法。
8
最後,隨便試一下,用『abc』也可以,哈哈。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/280742.html