Python-lambda function

Reference learning: Liao Xuefeng python's official website

First introduce a function map()

map() will map the specified sequence according to the provided function.

The first parameter function calls the function function with each element in the parameter sequence and returns a new list containing the return value of each function function.

Syntax: map(function,iterable,...)

parameter

(Refer to the rookie tutorial)

>>> def square(x):            #Calculate the square number
... return x **2...>>>map(square,[1,2,3,4,5])   #Calculate the square of each element of the list
[1,4,9,16,25]>>> map(lambda x: x **2,[1,2,3,4,5])  #Use lambda anonymous functions
[1,4,9,16,25]
 
# Two lists are provided to add the list data at the same position
>>> map(lambda x, y: x + y,[1,3,5,7,9],[2,4,6,8,10])[3,7,11,15,19]

Began to introduce lambda anonymous functions

When we pass in a function, sometimes it is not necessary to explicitly define the function, and it is more convenient to pass in an anonymous function directly. In Python, there is limited support for anonymous functions. Take the map() function as an example. When calculating f(x)=x2, in addition to defining a function of f(x),

You can also directly pass in anonymous functions:

>>> list(map(lambda x: x * x,[1,2,3,4,5,6,7,8,9]))[1,4,9,16,25,36,49,64,81]

It can be seen from the comparison that the anonymous function lambda x: x * x is actually:

def f(x):return x * x

The keyword lambda represents an anonymous function, and the x before the colon represents the function parameter.

Anonymous functions have a limitation, that is, there can only be one expression, without writing return, the return value is the result of the expression.

There is an advantage to using anonymous functions, because the function has no name, so there is no need to worry about function name conflicts. In addition, an anonymous function is also a function object. You can also assign an anonymous function to a variable, and then use the variable to call the function:

>>> f = lambda x: x * x
>>> f
< function<lambda> at 0x101c6ef28>>>>f(5)25

Similarly, anonymous functions can also be returned as return values, such as:

def build(x, y):return lambda: x * x + y * y

An exercise example of anonymous functions:

( Change this function to lambda expression)

def is_odd(n):return n %2==1

L =list(filter(is_odd,range(1,20)))

Lambda after the change

Recommended Posts

Python-lambda function
Python enumerate() function
Python function buffer