在编程语言中 switch 语句是比较常见的一种语法,但是python却摒弃了switch 官方的建议是使用 if-elif-…-else来代替,但是如果就是想用switch怎么办呢,也有方法
方法一:使用dict字典实现
def switch(arg):
sw = {0:"zero",1:"one",3:"three"}
# 参数一:要传入的参数arg,参数二:默认值,当dict中没有对应的arg的键值的时候使用该默认值
return sw.get(arg,"nothing")
print(switch(8))
方法二:使用lambda表达式实现
switch = {"a":lambda x:x * 2,"b":lambda x:x * 3,"c":lambda x:x ** x}
try:
# ['x'](y):x表示dict的key,y表示key对应的value的lambda表达式的参数
print(switch["a"](4))
except KeyError as e:
pass
创建自己的类来实现
该方法一般不实用,太麻烦。。。
# 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