发布时间:2022-03-01 09:35:10 人气:212 作者:多测师
python中没有现成的swith --- case 控制流,可以通过如下方法实现:
一:通过字典实现
type="sms"
advtype={
"sms":"select id from advertising where dtype like 'SMSAdvertising' ORDER BY RAND() limit 0,1",
"mms":"select id from advertising where dtype like 'MMSAdvertising' ORDER BY RAND() limit 0,1",
"mma":"select id from advertising where dtype like 'MMAAdvertising' ORDER BY RAND() limit 0,1",
"page":"select id from advertising where dtype like 'PageAdvertising' ORDER BY RAND() limit 0,1",
"installer":"select id from advertising where dtype like 'InstallerAdvertising' ORDER BY RAND() limit 0,1"
}
print advtype.get(type.lower())
二、通过自编类或者函数实现(这个有点麻烦,但是也更灵活)
class switch(object):
def __init__ (self,value): #初始化需要匹配的值value
self.value=value
self.fall=False #如果匹配到的case语句中没有break,则fall为true.
def __iter__ (self):
yield self.match #调用match方法,来返回一个生成器
raise StopIteration #StopIteration异常来判断for循环是否结束
def match (self,*args):
if self.fall or not args: #模拟case子句的方法
return True #如果fall为true,则继续执行下面的case子句或case子句没有匹配项,则流转到默认分支
elif self.value in args: #匹配成功
self.fall=True
return True
else: #匹配失败
return False
operator="+"
x=1
y=2
for case in switch(operator):
if case("+"):
print x+y
break
if case("-"):
print x-y
break
if case("*"):
print x*y
break
if case("/"):
print x/y
break
else:
print ""
以上内容为大家介绍了python的switch实现,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/