众所周知,Python的语法里没有像C语言中的switch…case…语法结构,所以有时候当我们想要用这个语法时不免捉急。不过不用怕,Python的dict数据结构有时能够很好地帮助我们实现switch…case…结构。
我们以下面一段程序为例来说明:
def operation(a,b,op):
if op == '+':
return a+b
if op == '-':
return a-b
if op == '*':
return a*b
if op == '/':
return a/b
if __name__ == '__main__':
a=1
b=2
print('a+b=', operation(a,b,'+'))
print('a-b=', operation(a,b,'-'))
print('a*b=', operation(a,b,'*'))
print('a/b=', operation(a,b,'/'))
在上面的程序中,因为Python本身缺少switch…case…语法,因此只能使用if语句,但这样会造成很大的不便和浪费。我们尝试着用dict(字典)来解决这个问题。代码如下:
def operation(a,b,op):
op_dict = {'+':a+b, '-':a-b, '*':a*b, '/':a/b,}
return op_dict[op]
if __name__ == '__main__':
a=1
b=2
print('a+b=', operation(a,b,'+'))
print('a-b=', operation(a,b,'-'))
print('a*b=', operation(a,b,'*'))
print('a/b=', operation(a,b,'/'))
在上面的程序中,我们利用dict数据结构的key-value对即可实现switch…case…语法,由此可以看出这种方法的简洁和便利。
当然这仅仅只是一个例子,有兴趣的同学可以多多尝试,说不定能找到更多dict的妙用~~
本次分享到此结束,欢迎交流与批评~~