How to use python lambda?
python uses lambda to create anonymous functions.
lambda is just an expression, and the function body is much simpler than def.
The body of lambda is an expression, not a code block. Only limited logic can be encapsulated in lambda expressions.
The lambda function has its own namespace and cannot access parameters outside its own parameter list or in the global namespace.
Although the lambda function seems to only be able to write one line, it is not equivalent to the inline function of C or C. The purpose of the latter is to not occupy the stack memory when calling a small function and thus increase the operating efficiency.
Grammar
The syntax of the lambda function only contains one statement, as follows:
lambda [arg1 [,arg2,.....argn]]:expression
Example (Python 2.0)
#!/usr/bin/python # -*- coding: UTF-8 -*- # 可写函数说明 sum = lambda arg1, arg2: arg1 + arg2; # 调用sum函数 print "相加后的值为 : ", sum( 10, 20 ) print "相加后的值为 : ", sum( 20, 20 )
Output results of the above examples:
相加后的值为 : 30 相加后的值为 : 40
Related recommendations: "Python Tutorial"
The above is the detailed content of How to use python lambda. For more information, please follow other related articles on the PHP Chinese website!