lambda Expression Introduction
python There is a kind of flexibility in , A convenient and functional expression :lambda expression !
lambda expression , Also called anonymous function , It is a grammar introduced by various modern programming languages , Its function is comparable to function , Design is simpler than function .
python lambda expression
If a function is named 、 Code blocks that are easy to reuse , that lambda Expressions are more flexible blocks of code , It can be passed and called in the program .lambda Expressions can be used to replace local functions ( Interested readers can refer to “ Local function ”), Let's show you lambda How to use expressions .
lambda Expression definition
First of all, let's take a code example to let you know lambda Expressions have an intuitive understanding of :
lambda Expression example 1
As can be seen from the above code example ,lambda The syntax format of the expression is :
lambda [parameter_list] : According to its grammatical format, an expression can get lambda Two points of expression :
lambda Expression must use lambda Keyword definition . stay lambda After keyword 、 To the left of the colon is a list of parameters , Without parameters , There can also be multiple parameters . If you have more than one parameter , Parameters are separated by commas , To the right of the colon is lambda Return value of expression .lambda The nature of expressions is anonymous 、 A function of a single function body , so lambda Expressions can be written as functions . for example , For the following lambda expression :
lambda x , y : x * y Rewrite it into a function in the form of :
def add(x, y):return x * y
That is, function definition can be simplified : When the function body has only one line of code , You can put the code body of the function on the same line as the function header .
One lambda Example expression
In this example, a variety of python Tips , Include python The derived type ,map function ,lambda Expression etc. .
lambda Expression example 2
A problem : Interested readers can write all the above code , Deep understanding lambda expression .
summary
by comparison ,python Medium function ratio lambda Expressions are more functional and adaptable ,lambda An expression is simply a function whose body is a line of code , So what it creates is a simple function object .
But I have to say that ,lambda Expressions still have the following advantages :
For single line code functions , Use lambda Expressions can eliminate the complex process of defining functions , Make your code cleaner . For functions that don't need to be used many times , because lambda The characteristic of an expression that is released immediately after it is used up , Improved program performance lambda The expression in python It's very useful , I hope that the explanation of this article will be helpful to the readers python Help ! Thank you for reading !
thank you