python (10): lambda function

 lambda is an anonymous function that returns a default expression, does not require a handwritten return.

lambda [参数]: 表达式

No parameter lambda expression: 

s = lambda : 'hhh'
print(s())
'''
输出:
hhh
'''

There are parameters lambda expression:

s = lambda x: x*2
print(s(3))
'''
输出:
6
'''

There are two parameters of the lambda expression:

s = lambda x, y: x ** y
print(s(3, 2))
'''
输出:
9
'''

lambda functions can only be a simple function, a line can not be included for or if.

Only under such circumstances can be used if,

I.e., vectorization ternary operator: if condition contents when the contents else condition is satisfied when the condition is not satisfied.

s = lambda x, y: x if x > y else y
print(s(3, 2))
'''
输出:
3
'''

 

 

 

Guess you like

Origin blog.csdn.net/qq_26271435/article/details/89713614