A Brief Introduction to lambda expressions and pythonlambda expressions in python
Recently, coding found that using lambda still has many advantages. In many cases, the code is more neat and pythonic, so here is a brief summary.
1. What is lambda?
A simple example:
func = lambda x: x*xdef func(x): return x*x
The two func definitions are exactly the same. The two function definition methods are used together with map to calculate the square of all elements in the list and what the code will look like,
def func(x): return x*xmap(func, [i for i in range(10)])map(lambda x: x*x, [i for i in range(10)])
In contrast, the effect is obvious. First of all, func functions are very simple and may only be used this time. So here we define a function that is simple and rarely used. In this example, creating an anonymous function using lambda does not affect the readability of the Code, but also streamline the code and reduce unnecessary function calls. In fact, this scenario is very common. We need a simple single-line function to do a simple thing. We don't even need to care about the function name. lambda is our good choice at this time.
2. Whether to use lambda
Lambda defines an anonymous function, which does not improve code execution efficiency. Lambda is usually used with map, reduce, and filter when traversing the list. However, the blind pursuit of lambda is often disastrous for code readability. Python has strict restrictions on lambda. After all, it can only consist of one expression. Lambda is easy to use, but if it is used too much, the logic of the program may not seem so clear. After all, everyone has different understandings of abstraction.
If a list is generated, only for, if, and in can be used. I will not use lambda.
If the function is not simple enough and involves complex logic such as loops, I will define the function to make the code more readable. At this time, I will not use lambda
In my opinion, lambda exists to reduce the definition of a single-row function, so it is enough to replace the definition of a single-row function.