[detailed explanation] anonymous function lambda in python

preface

Lambda functions are frequently used in python. Let's learn lambda functions today.

1, lambda syntax

The syntax of lambda function can only contain one statement. The format is as follows:

lambda [arg1 [,arg2,...argn]]:expression

lambda is the keyword reserved by python, arg1... argn is the parameter list, and expression is the function expression.

add = lambda : 10
print(add())# 10

Our parameter list can even be empty.
Our common parameter list is as follows:

a, b
a=1, b=2
*args
**kwargs
a, b=1, *args
 empty
......

The parameter list is the same as the parameter list of the function we normally define. It can be any parameter and supports all data types supported by python.

Expression is a parameter expression. The parameters appearing in the expression need to be defined in [arg...], and the expression can only be single line and there can only be one expression.

1
None
a + b
sum(a)
1 if a >10 else 0
......

The following lambda functions:

add = lambda x,y:x+y
print(add(1,3))# 4

When calling the function defined by lambda, we all return the calculation result of parameter expression.

2, Characteristics of lambda function

1. lambda functions are anonymous:
The so-called anonymous function is a function without a name. lambda function has no name.

2. lambda functions have inputs and outputs:
The input is the argument passed into the parameter list_ List, and the output is the value calculated according to the expression.

3. lambda functions have their own namespace:
You cannot access parameters outside your parameter list or in the global namespace. You can only complete very simple functions.

Examples of common lambda functions:

lambda x, y: x*y			# The function inputs are x and y, and the output is their product x*y
lambda:None					# The function has no input parameters and the output is None
lambda *args: sum(args)		# The input is an arbitrary number of parameters, and the output is their sum (implicitly requires that the input parameters must be able to perform arithmetic operations)
lambda **kwargs: 1			# The input is any key value pair parameter, and the output is 1

3, Common usage of lambda

Since the syntax of lambda is fixed, there is essentially only one usage, that is, to define a lambda function.
According to different application scenarios, the common usage is summarized as follows:

1. Assign a lambda function to a variable, and call the lambda function indirectly through this variable.

add = lambda x, y: x+y

It is equivalent to defining the addition function lambda x, y: x+y and assigning it to the variable add, so that the variable add points to the function with addition function.
At this time, if we execute add(1, 2), the output result will be 3.

2. Assign a lambda function to another function and replace the other functions with this lambda function.

# In order to mask the function of sleep in the standard library time (Mock), we can call during program initialization:
time.sleep=lambda x: None
# In this way, calling the sleep function of the time library in subsequent code will not perform the original functions.
# For example:
time.sleep(3)	# The program will not sleep for 3 seconds, but because the lambda output is None, the result here is nothing

4, Higher order function of lambda usage

map() function:
Description:
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, ...)
Parameters:
Function ----- > function
Iterable ---- > one or more sequences
Return value:
Python 2. Version x returns a list
Python 3. The version returned by the iterator is X

Example:

# ===========General writing:===========
# 1. Calculate square
def square(x):
	return x ** 2

map(square, [1,2,3,4,5])	# Calculate the square of each element of the list
# result:
[1, 4, 9, 16, 25]

# ===========Anonymous function writing method:============
# 2. Calculate the square, lambda
map(lambda x: x ** 2, [1, 2, 3, 4, 5])
# result:
[1, 4, 9, 16, 25]	 

# 3. Provide two lists and add the list elements with the same index position
map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
# result:
[3, 7, 11, 15, 19]

reduce() function:
Description:
The reduce() function accumulates the elements in the parameter sequence.
The function performs the following operations on all data in a data set (linked list, tuple, etc.): first operate the first and second elements in the set with the function (with two parameters) passed to reduce, and then operate with the third data with the function function, and finally get a result.

Syntax:
reduce(function, iterable[, initializer])
Parameters:
Function ----- > function, with two parameters
Iteratable ---- > iteratable object
Initializer ---- > optional, initial parameter
Return value:
Returns the calculation result of the function.

Example:

# ===========General writing:===========
# 1. Add two numbers
def add(x, y):            
	return x + y

reduce(add, [1, 3, 5, 7, 9])    # Calculate list elements and: 1 + 3 + 5 + 7 + 9
# result:
25

"""
===========Perform step parsing:===========
call reduce(add, [1, 3, 5, 7, 9])When, reduce The function will calculate as follows:
1	First calculate the first two elements: f(1, 3),The result is 4;
2	Then calculate the result and the third element: f(4, 5),The result is 9;
3	Then calculate the result and the fourth element: f(9, 7),The result was 16;
4	Then calculate the result and the fifth element: f(16, 9),The result was 25;
5	Since there are no more elements, the calculation ends and the result 25 is returned.
"""
# ===========Anonymous function writing method:===========
# 2. Add two numbers, lambda writing
reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
# result:
15

# Of course, the Python built-in function sum() can be directly used for summation operation, and there is no need to use reduce.
	
# 3. However, if you want to convert the sequence [1, 3, 5, 7, 9] into an integer 13579, reduce can come in handy:
from functools import reduce

def fn(x, y):
	return x * 10 + y

reduce(fn, [1, 3, 5, 7, 9])
# result:
13579

sorted() function:
Description:
The sorted() function sorts all iteratable objects.

Difference between sort and sorted:
Sort is a method of list, and sorted can sort all iteratable objects.
The sort method of list returns the operation on the existing list without return value, while the built-in function sorted method returns a new list instead of the operation on the original basis.

Syntax:
sorted(iterable[, cmp[, key[, reverse]]])
Parameter Description:
Iteratable ---- > iteratable object.
CMP ---- > the function of comparison has two parameters. The values of the parameters are taken from the iteratable object. The rules that this function must abide by are: if it is greater than, it returns 1, if it is less than, it returns - 1, and if it is equal to, it returns 0.
Key ---- > is mainly used to compare elements. There is only one parameter. The parameters of the specific function are taken from the iteratable object. Specify an element in the iteratable object to sort.
Reverse ---- > collation, reverse = True descending, reverse = False ascending (default).
Return value:
Returns a reordered list.

# ===========General usage:===========
# 1. Simple sorting
a = [5,7,6,3,4,1,2]
b = sorted(a)       # Use sorted to keep the original list without changing the value of list a
print(a)
[5, 7, 6, 3, 4, 1, 2]
print(b)
[1, 2, 3, 4, 5, 6, 7]

# ===========Anonymous function usage:===========
L=[('b',2),('a',1),('c',3),('d',4)]
# 2. Sorting by parameter cmp
sorted(L, cmp=lambda x,y:cmp(x[1],y[1]))
# result:
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# 3. Sort with parameter key
sorted(L, key=lambda x:x[1])
# result:
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

# 4. Ascending by age
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
sorted(students, key=lambda s: s[2])
# result:
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
# 5. In descending order of age
sorted(students, key=lambda s: s[2], reverse=True)
# result:
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
# 6. Sort Dictionaries
leaders = {4: "Yang Zhou", 2: "Elon Musk", 3: "Tim Cook", 1: "Warren Buffett"}
print(leaders)
# {4: 'Yang Zhou', 2: 'Elon Musk', 3: 'Tim Cook', 1: 'Warren Buffett'}
leaders = dict(sorted(leaders.items(), key=lambda x: x[0]))
print(leaders)
# {1: 'Warren Buffett', 2: 'Elon Musk', 3: 'Tim Cook', 4: 'Yang Zhou'}

filter() function:
Description:
The filter() function is used to filter the sequence, filter out the elements that do not meet the conditions, and return a new list composed of qualified elements.

The receives two parameters. The first is a function and the second is a sequence. Each element of the sequence is passed to the function as a parameter for judgment, and then returns True or False. Finally, the element that returns True is placed in the new list.
Syntax:
filter(function, iterable)
Parameters:
Function ----- > judgment function.
Iteratable ---- > iteratable object.
Return value:
Pyhton2.7 return to the list, python 3 X returns the iterator object. For details, see the python 3 filter() function

# ===========General usage:===========
# 1. Filter out all odd numbers in the list
def is_odd(n):
	return n % 2 == 1
		 
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(list(newlist))
# Result: [1, 3, 5, 7, 9]

# ===========Anonymous function usage:===========
# 2. Filter out the elements in the list [1, 2, 3] that can be divided by 3
newlist = filter(lambda x: x % 3 == 0, [1, 2, 3])
print(list(newlist))
# Result: [3]

Tags: Python programming language

Posted by csudhoff on Tue, 17 May 2022 02:50:19 +0300