python中Switch/Case实现的示例代码
学习Python过程中,发现没有switch-case,过去写C习惯用Switch/Case语句,官方文档说通过if-elif实现。所以不妨自己来实现Switch/Case功能。
使用if…elif…elif…else实现switch/case
可以使用if…elif…elif..else序列来代替switch/case语句,这是大家最容易想到的办法。但是随着分支的增多和修改的频繁,这种代替方式并不很好调试和维护。
方法一
通过字典实现
deffoo(var):
return{
'a':1,
'b':2,
'c':3,
}.get(var,'error')#'error'为默认返回值,可自设置
方法二
通过匿名函数实现
deffoo(var,x):
return{
'a':lambdax:x+1,
'b':lambdax:x+2,
'c':lambdax:x+3,
}[var](x)
方法三
通过定义类实现
参考BrianBeck通过类来实现Swich-case
#Thisclassprovidesthefunctionalitywewant.Youonlyneedtolookat
#thisifyouwanttoknowhowthisworks.Itonlyneedstobedefined
#once,noneedtomuckaroundwithitsinternals.
classswitch(object):
def__init__(self,value):
self.value=value
self.fall=False
def__iter__(self):
"""Returnthematchmethodonce,thenstop"""
yieldself.match
raiseStopIteration
defmatch(self,*args):
"""Indicatewhetherornottoenteracasesuite"""
ifself.fallornotargs:
returnTrue
elifself.valueinargs:#changedforv1.5,seebelow
self.fall=True
returnTrue
else:
returnFalse
#Thefollowingexampleisprettymuchtheexactuse-caseofadictionary,
#butisincludedforitssimplicity.Notethatyoucanincludestatements
#ineachsuite.
v='ten'
forcaseinswitch(v):
ifcase('one'):
print1
break
ifcase('two'):
print2
break
ifcase('ten'):
print10
break
ifcase('eleven'):
print11
break
ifcase():#default,couldalsojustomitconditionor'ifTrue'
print"somethingelse!"
#Noneedtobreakhere,it'llstopanyway
#breakisusedheretolookasmuchliketherealthingaspossible,but
#elifisgenerallyjustasgoodandmoreconcise.
#Emptysuitesareconsideredsyntaxerrors,sointentionalfall-throughs
#shouldcontain'pass'
c='z'
forcaseinswitch(c):
ifcase('a'):pass#onlynecessaryiftherestofthesuiteisempty
ifcase('b'):pass
#...
ifcase('y'):pass
ifcase('z'):
print"cislowercase!"
break
ifcase('A'):pass
#...
ifcase('Z'):
print"cisuppercase!"
break
ifcase():#default
print"Idunnowhatcwas!"
#AssuggestedbyPierreQuentel,youcanevenexpanduponthe
#functionalityoftheclassic'case'statementbymatchingmultiple
#casesinasingleshot.Thisgreatlybenefitsoperationssuchasthe
#uppercase/lowercaseexampleabove:
importstring
c='A'
forcaseinswitch(c):
ifcase(*string.lowercase):#notethe*forunpackingasarguments
print"cislowercase!"
break
ifcase(*string.uppercase):
print"cisuppercase!"
break
ifcase('!','?','.'):#normalargumentpassingstylealsoapplies
print"cisasentenceterminator!"
break
ifcase():#default
print"Idunnowhatcwas!"
#SincePierre'ssuggestionisbackward-compatiblewiththeoriginalrecipe,
#Ihavemadethenecessarymodificationtoallowfortheaboveusage.
查看Python官方:PEP3103-ASwitch/CaseStatement
发现其实实现SwitchCase需要被判断的变量是可哈希的和可比较的,这与Python倡导的灵活性有冲突。在实现上,优化不好做,可能到最后最差的情况汇编出来跟IfElse组是一样的。所以Python没有支持。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。