Article directory
- Anonymous functions, higher-order functions, modules, packages
-
-
-
- 1.Anonymous function
- 2. Actual parameter higher-order functions
- 3. Common high-order functions with actual parameters in python
- **1) max(container, function)**
- **2) map(function, container <1 or more>)**
- **3) filter(function, container)**
- **4) reduce(function, container, initial value)**
- 3. Module import
- **Import principle:**
- **When the code of the imported module is executed, the system will automatically enter this module and execute all the code in this module. **
- **Place other codes to be executed outside the function below for judgment**
- **The code in the if statement will not be executed when someone else calls the module**
- Bag
-
- **1.What is a package**
- **2.Import modules in package/folder**
-
-
Anonymous functions, higher-order functions, modules, packages
1.Anonymous function
There is no difference from ordinary functions, except that the naming method is different. Anonymous functions have no names.
Note: Use anonymous functions when only one line of code can implement the function
Grammar:
Function name (essentially a variable) = lambda formal parameter list (at least one formal parameter): return value sum = lambda num1,num2=2: num1 + num2 print(sum(1,2))
2. Higher-order functions with actual parameters
A function whose parameters are functions is a higher-order function with actual parameters
When passing arguments to higher-order functions with actual parameters, you can use the function name of an ordinary function or use an anonymous function
3. Common high-order functions with actual parameters in python
max ;min; sorted; list.sort ; map; reduce; filter
max(container, *, key: function)
1) max (container, function)
Compare the sizes of elements in the container according to the rules set by the function to obtain the maximum value
Function requirements:
1) There is only one parameter, and this parameter represents each element in the previous container
2) There is only one return value, and the return value is the comparison object
# Exercise 1: Sort the names in names according to length from smallest to largest names = ['Li Xiaoming', 'Zhang San', 'Gulireba', 'Xiaohua', 'Wang Dafu'] print(sorted(names, key=lambda item: len(item))) # Exercise 2: Find the oldest student among the students students = [ {<!-- -->'name': 'Zhang San', 'score': 38, 'age': 18}, {<!-- -->'name': 'Xiao Ming', 'score': 99, 'age': 25}, {<!-- -->'name': '李思', 'score': 89, 'age': 19}, {<!-- -->'name': 'Laowang', 'score': 70, 'age': 30}, {<!-- -->'name': '小花', 'score': 65, 'age': 26} ] print(max(students, key=lambda stu: stu['age']))
2) map (function, container <1 or more>)
Convert the elements in the container into a new container based on function conditions, The new container is a special container, It needs to be converted into a container we know
**Function requirements:**a. Have and only one parameter, which represents each element in the container
? b. Requires a return value, the return value is the element in the new container
map(function, container 1, container 2)
**Function requirements: **a. Have and only two parameters, represent each element in the following two containers
? b. Requires a return value, the return value is the element in the new container
map(function, container 1, container 2,…container n)
**Function requirements: **a. Have and only n parameters, represent each element in the following n containers
? b. Requires a return value, the return value is the element in the new container
# Exercise 1: Extract the single digits of all elements in nums nums = [19, 108, 44, 37, 82, 91, 86] result = list(map(lambda item: item % 10, nums)) print(result) # Exercise 2: Convert the points in scores into corresponding passing relationships scores1 = [90, 56, 89, 99, 45, 34, 87] # ['Passed', 'Not Passed', 'Passed', ....] result = list(map(lambda item: 'passed' if item >= 60 else 'not passed', scores1)) print(result) # Exercise 3: Use the units digit of the element in nums1 as the tens digit of the element in the new container, and use the tens digit of the element in nums2 as the units digit of the element in the new container. nums1 = [89, 34, 89, 20, 192, 93] nums2 = [102, 89, 37, 82, 26, 1293] # [90, 48, 93, 8, 22, 39] result = list(map(lambda item1, item2: item1 % 10 * 10 + item2 // 10 % 10, nums1, nums2)) print(result) # Exercise 4: Given two lists A and B, use the map function to create a dictionary. The elements in A are keys and the elements in B are values. # Convert tuple/list to dictionary A = ['name', 'age', 'sex'] B = ['Zhang San', 18, 'Female'] # New dictionary: {'name': 'Zhang San', 'age': 18, 'sex': 'female'} print(dict(map(lambda a, b: (a, b), A, B)))
3) filter (function, container)
Extract all elements in the container that meet the function conditions
**Function requirements:**a. Have and only one parameter, which represents each element in the container
? b. Requires a return value, and the return value is the corresponding extraction condition
# Exercise 1: Extract all Chinese characters in the string str1 = 'sjs health os02-technically ss=2e block' result = filter(lambda item: '\\一' <= item <= '\\龥', str1) print(''.join(result))
4) reduce (function, container, initial value)
Combine the elements in the container into one data according to function conditions
**Function requirements: **a. Have and only two parameters, The first one points to the initial value, and the second one points to each element in the container
? b. Requires a return value, which is Merge rule
reduce needs to be imported from the functools module
from functools import reduce nums = [2, 3, 4, 5, 1] # Set different initial values according to different merging methods # 2 + 3 + 4 + 5 + 1 initial value is 0 # 2*3*4*5*1 initial value is 1 # 23451 The initial value is ''
# Exercise 1: Find the single-digit sum of all elements in nums from functools import reduce scores = [90, 56, 89, 99, 45, 34, 87] result = reduce(lambda i, item: i + item % 10, scores, 0) print(result) # Exercise 2: Find the total scores of all students in students students = [ {<!-- -->'name': 'Zhang San', 'score': 38, 'age': 18}, {<!-- -->'name': 'Xiao Ming', 'score': 99, 'age': 25}, {<!-- -->'name': '李思', 'score': 89, 'age': 19}, {<!-- -->'name': 'Laowang', 'score': 50, 'age': 30}, {<!-- -->'name': '小花', 'score': 65, 'age': 26} ] result = reduce(lambda i, stu: i + stu['score'], students, 0) print(result)
3. Module import
Import method:
a) import module name Module name.xx
b) from module name import content 1, content 2, … You can directly use the corresponding content in the imported module
**c) from module name import *** can directly use all contents in the module
d) from module name as xx module rename, module name is too long, etc.
e) from module name import content as new content name Content
Import principle:
When the code of the imported module is executed, the system will automatically enter this module and execute all the code in this module.
Place other codes to be executed outside the function under the judgment below
if __name__ == '__mian__': # __read->'Dang嘚' below->Dang嘚name
The code in the if statement will not be executed when someone else calls the module
Package
1. What is a package
# The package is the folder containing the __init__.py file
2. Import modules in packages/folders
a) import package name After importing the specified package, use ‘Package name.xxx‘ to use any content in the init.py file in the package
b) import package name.module name Import the specified module in the specified package, use ‘package name.module name.xxx‘ to use all the content in the module, you can Rename directly for convenience
c) from package name import module name 1, module name 2, content 1, content 2,… ’Module name. Content’ ’Content’ – direct call
d) from package name.module name import content 1, content 2,… Import the specified module in the specified package, and you can use the content directly