One, lambda expression
1 >>> def add (x, y): #定义一个加法函数 2 return x+y #返回两个参数的相加的值 3 4 >>> z=f (3, 4) 5 >>> print (z) 6 7 #调用加法函数返回7 7 >>> Lambda x,y:x+ Y 8 <function <lambda> at 0x0000020f385b86a8> 9 #可以看到lambda是一个 function (function) class object >>> F=lambda x , Y:x+y #功能实现的跟add (x, y) >>> f (313 >>> f (3,4) 715 >>> def multiply ( X, y): return x*y17 >>> Multiply (3,4) 1220 >>> multiply=lambda X,y:x*y21 >>> Multiply (3,4) 1223 >>> def subtract (x, y): Return x-y25 >>> Subtract (3,4) 27-128 >>> subtract =lambda x,y:x-y29 >>> Subtract (3,4) 30-131 >>> def divide (x, y): return x/y34 >>> di Vide (4,2) 2.037 >>> divide=lambda x,y:x/y38 >>> Divide (4,2) 2.040 #上面的乘法函数, subtraction function, The Division function can be replaced with a lambda expression, which is more convenient for
As you can see from the above, lambda expressions can be conveniently used instead of simple functions.
Two or three-dollar operation
1, see what is ternary operation
2, Python's ternary operation format is as follows:
result= value 1 if x<y else value 2 What does this mean, is the result = value 1 if condition 1 else value 2
1 >>> def f (x, y): 2 return x-y if x>y else abs (x-y) 3 #如果x大于y就返回x-y value, otherwise it returns the absolute number of X-y 4 5 > >> f (3,4) #3 <4, does not meet the IF condition, it returns the absolute value inside the Else 6 >>> F (4,3) 7 >>> def f (x, y): 8 return 1 if X> Y else-1 9 #如果x大于y就返回x-y value, otherwise return -110 >>> f (3,4) #3小于4, returns -111-112 >>> f (4,3) #4大于3, returns 11 3 >>>
Python ternary operations and lambda