lambda function of python

  A lambda function is also called an anonymous function. An anonymous function is a function without a function name.

>>> lambda x,y:x+y
<function <lambda> at 0x7f0f0dd85578>

  x, y are the two variables of the function, located to the left of the colon, and the expression to the right of the colon is the return value of the function.

>>> add =lambda x,y:x+y
>>> add
<function <lambda> at 0x7f0f0dd855f0>
>>> add(1,2)
3

  is equivalent to a function

def add(x,y):
    return x+y
add(1,2)

  lambda usage scenarios

1. Functional programming
#For example: a list of integers, which is required to be sorted in ascending order according to the absolute value of the elements in the list
list1 = [3,5,-4,-1,0,-2,-6]
print(sorted(list1,key=abs))
print(sorted(list1,key=lambda x:abs(x)))

2. The most common filter filtering, map brushes, and reduce merging in python can be generated by lambda expressions. For sequences, there are three functional programming tools: filter(), map(), reduce()
map(function,sequence): Pass the values ​​in the sequence as parameters to the function one by one, and return a list containing the execution results of the function. If function has two parameters, namely map(function,sequence1,sequence2).
#Square 1 ~ 20
print(list(map(lambda x:x**2,range(1,21))))
#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]

filter(function,sequence): Execute function(item) on the items in the sequence in turn, and form a List/String/Tuple (depending on the type of sequence) of the items whose execution result is True and return.
#find even numbers between 1 and 20
print(list(filter(lambda x:x%2 == 0,range(1,21))))
#[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

reduce(function, sequence): The number of parameters received by the function can only be 2. First, pass the first value and the second value in the sequence as parameters to the function, and then use the return value and the third value of the function as parameters. Pass it to the function, and just return a result.
#Seek the sum of 1~100
from functools import reduce
print(reduce(lambda x,y:x+y,range(1,101)))
#5050

#Seek the sum of 1~100, plus 10000
from functools import reduce
print(reduce(lambda x,y:x+y,range(101),10000))
#15050

3. Closures
A function defined inside a function, the inner function uses the temporary variables of the outer function, and the return value of the outer function is a reference to the inner function.

def outer(a):
    b=10
        def inner(): # inner function
            print(a+b)
        return inner # The return value of the outer function is a reference to the inner function
outer(5)

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324690979&siteId=291194637