The ternary operator and Lambda Python
Lambda operation
Concept: No definition refers to a class identifier (function name) function or subroutine.
Features: Anonymous function does not use def-defined functions, using lambda to create an anonymous function
1.lambda just an expression, it is simpler than the function body def
2.lambda subject is an expression rather than a block of code, just only in the lambda expressions package simple logic
3.lambda function has its own namespace, and can not access the global name space outside the free parameters or parameter list (only with their own parameters, the other does not take)
lambda Syntax:
lambda parameter 1, parameter 2, ..., parameter n: expression [Expression]
= SUM the lambda num1, num2: + num1 num2 Print (SUM (. 1, 2 )) Output: 3
Lambda expressions and if not ... else usage
# If condition is true if the foregoing content returned, otherwise 0 EXP1 = the lambda X: X +. 1 if 2 ==. 1 the else 0 Print (EXP1 (2 )) EXP2 = the lambda X: X +. 1 if . 1. 1 == the else 0 Print (EXP2 (2 )) output: 0 . 3
# If not returns false if not foregoing content, otherwise 0 EXP3 = the lambda X: X +. 1 IF Not 2 ==. 1 the else 0 Print (EXP3 (2 )) EXP4 = the lambda X: X +. 1 IF Not . 1 == . 1 the else 0 Print (EXP4 (2 )) output: . 3 0
Ternary operator
a = 1 b = 2 h = "" h = "变量1" if a>b else "变量2" print(h)
# Normal conditional statement IF . 1. 1 == : name = 'Jack Ma ' the else : name = 'Pony ' # ternary operator name = 'Jack Ma ' IF the else. 1. 1 == ' Pony '
def whoIs_richest(jackMa='alibaba', pony='tencent'): return 'jackMa' if len(jackMa)>len(pony) else 'pony' print(whoIs_richest()) 输出: pony