As a high-level language, Python has the same feature of anonymous functions as many programming languages
anonymous function, also on the lambda expression, in layman's terms is not the method of naming, directly defined, directly use can
Creating an anonymous function requires the use of the Lambda keyword, and we are familiar with anonymous functions by creating a simple anonymous function
Lambda A,b:a + b
The value returned by this expression is the value of a plus B, and he needs to pass in two parameters, that is, a, a, a, and an expression, so that a complete anonymous function can be formed.
Through the code to refine this part of the understanding
In [1]: func = lambda a,b:a+bin [2]: Func out[2]: 3
First, as before, the anonymous function is assigned to an instance, and then this anonymous function is called by this instance.
Here's a few pieces of code
In [3]: def increment (n): ...: return lambda x:x+n ... : in [4]: func = Increment (5) in []: func (0) out[5]: 20In [6]: func (Ten) out[6]: 30
This is a simple increment function, n is the degree to be increased, and the lambda expression is a good way to implement such a function
In addition to returning a lambda expression as a function, you can also use it as a parameter preprocessing
For example, the following example
In [all]: Word_num = [(1, ' E '), (2, ' d '), (3, ' C '), (4, ' B '), (5, ' a ')]in []: word_num.sort (key = Lambda word_num:word_n UM[1]) in []: word_numout[13]: [(5, ' a '), (4, ' B '), (3, ' C '), (2, ' d '), (1, ' e ')]
Starting with a simple definition of a two-dimensional list, in the latter order, we specify that the reference to sort by the lambda expression is the second value, that is, the letter column, so he defaults to sort by the following letters.
The last returned nature is a list of well-ordered
This is the simple use of lambda expressions
My personal blog www.susmote.com
12_python (anonymous function) lambda expression _python programming path