在编程中,我们常常会遇到使用if…else的情况,某些语言中在if…else过多的时候我们会使用switch…case来替代if…else以避免代码结构过于冗长。
Python是不支持switch…case语法的,自然无法使用switch…case来替代if…else结构。
但好在强大的Python支持lambda, 本文就是介绍一种用lambda来替代if…else的方法实现。
先看看lambda 函数语法:
lambda [arg1 [, agr2,.....argn]] : expression
例如,我们要将两个字符串拼接并转为大写,可以这样实现:
In [80]: str1="hello"
...: str2="world"
...: str3="{}{}".format(str1.upper(), str2.upper())
...:
In [81]: str3
Out[81]: 'HELLOWORLD'
使用lambda函数可以这样做:
In [83]: cmb_str = lambda s1,s2:"{}{}".format(s1.upper(), s2.upper())
In [84]: str3=cmb_str(str1,str2)
In [85]: str3
Out[85]: 'HELLOWORLD'
了解了lambda的基本用法之后,我们来看看如何通过lambda来替代if…else。
假设我们要实现这样一个test()函数,分别处理val为1、2、3的情况,使用if…else实现如下:
In [86]: def test(val):
...: if val==1:
...: print("case 1")
...: elif val==2:
...: print("case 2")
...: elif val==3:
...: print("case 3")
...:
In [87]: test(1)
case 1
In [88]: test(2)
case 2
In [89]: test(3)
case 3
使用lambda可以这样来实现:
In [90]: def case1():
...: print("case 1")
...:
In [91]: def case2():
...: print("case 2")
...:
In [92]: def case3():
...: print("case 3")
...:
In [93]:
In [93]: def testLambda(val):
...: valfunc = {
...: 1: lambda:case1(),
...: 2: lambda:case2(),
...: 3: lambda:case3()}
...: func = valfunc[val]
...: func()
...:
In [94]: testLambda(1)
case 1
In [95]: testLambda(2)
case 2
In [96]: testLambda(3)
case 3
这可以在一定程度上使代码更为简洁。