preface
- ๐ฅ Author introduction: high quality creator and data development engineer in Python field
- ๐ฅณ Inspirational to become a Python full stack engineer, pay attention to me and find more wonderful~
- ๐ฃ This article has been included in the Python full stack series column: 100 days proficient in Python, from entry to employment
- ๐ Welcome to subscribe. After subscribing, you can chat privately into the Python stack communication group (hand-in-hand teaching and problem solving); You can also get 80GPython full stack tutorials: foundation, Web, crawler, data analysis, visualization, machine learning, deep learning, artificial intelligence, algorithm, interview questions, etc
- ๐ช Join me to learn and make progress. A person can go fast and a group of people can go further!
1, Introduction to lambda function
Sometimes when using a function, you do not need to assign a name to the function. The function is "anonymous function". In Python, lambda expressions are used to represent anonymous functions. The syntax for declaring lambda expressions is as follows:
lambda parameter list: lambda body
Lambda is a keyword declaration. In lambda expression, the "parameter list" is the same as the parameter list in the function, but it does not need to be enclosed in parentheses. After the colon is the lambda body. The main code of lambda expression is written in the lambda body, which is similar to the function body.
Tip: the lambda body cannot be a code block, cannot contain multiple statements, and can only contain one statement. The statement calculates a result and returns it to the lambda expression, but unlike the function, it does not need to use the return statement to return. Moreover, when using functions as parameters, lambda expressions are very useful, which can make the code simple and concise.
2, The difference between lambda function and def function
-
1. lambda can be passed immediately (without variables) and automatically return results;
-
2. lambda can only contain one line of code internally;
-
3. lambda is designed to write simple functions, while def is used to handle larger tasks;
-
4. lambda can define an anonymous function, and the function defined by def must have a name.
Advantages of lambda function:
-
1. For single line functions, using lambda expressions can save the process of defining functions and make the code more concise;
-
2. For functions that do not need to be reused many times, lambda expressions can be released immediately after they are used up, so as to improve the performance of program execution.
3, lambda function case
3.1 definition of addition function
# def function writing method def add(a, b): return a + b print(add(10, 20)) print("----------This is a dividing line----------") # lambda function writing method add_lambda = lambda a, b: a + b print(add_lambda(10, 20))
Output result:
30 ----------This is a dividing line---------- 30
3.2 using if to judge parity
# def function writing method def get_odd_even(x): if x % 2 == 0: return "even numbers" else: return "Odd number" print(get_odd_even(10)) print("----------This is a dividing line----------") # lambda function writing method get_odd_even1 = lambda x: "even numbers" if x % 2 == 0 else "Odd number" print(get_odd_even1(10)) print(get_odd_even1(9))
Output result:
even numbers ----------This is a dividing line---------- even numbers Odd number
3.3 nonparametric expression
# def function writing method def test1(): return "Python YYDS!!!" print(test1()) print("----------This is a dividing line----------") # lambda function writing method test2 = lambda: "Python YYDS!!!" print(test2())
Output result:
Python YYDS!!! ----------This is a dividing line---------- Python YYDS!!!
3.4 list sorting
# Sort according to the first number in the tuple a = [(2, "Xiao Hei"), (5, "Xiaobai"), (1, "Zhang San"), (4, "Li Si"), (3, "Wang Wu")] a.sort(key=lambda x: x[0]) print(a)
Output result:
[(1, 'Zhang San'), (2, 'Xiao Hei'), (3, 'Wang Wu'), (4, 'Li Si'), (5, 'Xiaobai')]
In the above example, the original disordered data is sorted according to the first element of the list. Tuples and dictionaries can be used in the same way!
3.5 map method mix and match (common)
Traverse the sequence, operate on each element in the sequence, and finally obtain a new sequence
# def function writing method def add(num): return num ** 2 x = map(add, [1, 2, 3, 4, 5]) print(list(x)) print("----------This is a dividing line----------") # lambda function writing method y = map(lambda num: num ** 2, [1, 2, 3, 4, 5]) print(list(y))
Output result:
[1, 4, 9, 16, 25] ----------This is a dividing line---------- [1, 4, 9, 16, 25]
In the above example, the first parameter of the map function is a lambda expression. Enter a parameter and return the square of the element. The second is the object to be used. Here is a list. Map in Python 3 returns a map object. We need to manually convert it into a list, and the result is [1, 4, 9, 16, 25]
3.6 filter method mix and match (common)
Filter the elements in the sequence and finally obtain the qualified sequence
x = filter(lambda num: num % 2 == 0, range(10)) print(list(x)) # [0, 2, 4, 6, 8]`
In the above example, a lambda expression is defined to filter even elements, and the result is [0, 2, 4, 6, 8].
3.7 mix and match of reduce methods (common)
Accumulate all elements in the sequence; The global reduce function is deleted from Python 3 and needs to be introduced from functools
from functools import reduce list1 = [1, 2, 3, 4, 5] list2 = reduce(lambda x, y: x + y, list1) print(list2) # 15
The lambda expression used in reduce requires two parameters. The reduce function has three parameters. The first is the lambda expression, the second is the sequence to be accumulated, and the third is the initial value. If we do not give the initial value, the first two elements of the sequence are the first two elements of the sequence. Otherwise, we will use the initial value given by us and the first element of the sequence to operate, and then the result will operate with the third element, and so on. The result of the last example is 15
4, lambda function summary
1. lambda is just an expression, and the function body is much simpler than def
2. The body of a lambda is an expression, not a code block. Only limited logic can be encapsulated in lambda expressions
3. lambda functions have their own namespace and cannot access parameters outside their own parameter list or in the global namespace
4. Simple single line code or one-time function can be written with lambda function, which can make the code more concise.
5. For complex functions or functions with large volume, it is best not to use lambda functions, which will increase the difficulty of reading the code and make the code obscure and difficult to understand.
6. In the case of functions that are not called multiple times, lambda expressions can be used to improve performance