current position:Home>Python notes - Day9 - higher order functions
Python notes - Day9 - higher order functions
2022-05-15 06:03:17【Wandering mage 12】
Preface
python Grammar learning , Leave it to those who need it , Understand everything !!
# coding=utf8
# @time:2022/4/15 15:04
# Author Haoyu
# 1. Functions are variables
# python Define function in , Is to define the type as function The variable of , The function name is the variable
'''''''''
a=10
b=lambda x:x*2
c={
'a':1,'b':2}
print(type(a),type(b),type(c)) # <class 'int'> <class 'function'> <class 'dict'>
'''''''''
# 1) One variable can assign a value to another variable
import time
'''''''''
x=100
y=x
print(y+100)
'''''''''
# 2) Change the value of the variable
# 3) Variables as elements of a sequence
'''''''''
x=100
list1=[x,200]
print(list1)
'''''''''
# 4) Variables as arguments to functions
# 5) Variable as the return value of the function
'''''''''
def func3():
def s():
print(' I'm a small function ')
return s
func3()()
'''''''''
'''''''''
# practice :
list3 = []
for i in range(5):
list3.append(lambda x:x*i)
print(list3[1](2)) # 8
print(list3[2](2)) # 8
'''''''''
# 2. Real argument higher order function
# A function whose parameter is a function is a higher-order function with real parameters
'''''''''
# func1 It's a higher-order function with real parameters
def func1(x):
print(x())
def func2(m=10):
print(' Hello ')
func1(func2)
'''''''''
# 3. The use of common higher-order functions in the system
# max、min、sorted、map、reduce
# max( Sequence ) - Compare the size of the elements in the sequence to get the element with the largest value
'''''''''
# 1)max、min
nums = [23,34,65,4,43,234,12]
print(max(nums)) - # 234
'''''''''
# max( Sequence ,key= function ) - The function determines the comparison object when the maximum value of the area
# Parameters key The requirements of :a. It's a function
# b. This function has one and only one parameter ( This parameter points to the elements in the sequence )
# c. Function should have a return value ( Comparison object )
'''''''''
# 2)max、min
nums = [23,34,65,4,43,234,12]
def f1(item):
return item%10
result = max(nums,key=f1)
print(result)
'''''''''
'''''''''
# Please say that there are the students with the highest scores among the students ?
students=[
{
'name':' Xiao Ming ','age':'27','score':'90'},
{
'name':' Xiaohong ','age':'53','score':'80'},
{
'name':' Little green ','age':'27','score':'70'},
{
'name':' The small white ','age':'22','score':'40'},
]
# def f2(item):
# return item['score']
# print(max(students,key=f2)) # {'name': ' Xiao Ming ', 'age': '27', 'score': '90'}
print(max(students,key=lambda item:item['score'])) #{'name': ' Xiao Ming ', 'age': '27', 'score': '90'}
'''''''''
'''''''''
# Ask the youngest of all students ?
students=[
{
'name':' Xiao Ming ','age':'27','score':'90'},
{
'name':' Xiaohong ','age':'53','score':'80'},
{
'name':' Little green ','age':'27','score':'70'},
{
'name':' The small white ','age':'22','score':'40'},
]
# def f3(item):
# return item['age']
# print(min(students,key=f3))
print(min(students,key=lambda item:item['age']))
'''''''''
'''''''''
# practice : Gets the largest element of the sum of each digit in the list ?
# nums=[23,78,80,72,233,91]
# 5,15,8,9,8,10 -> 78
nums=[23,78,80,72,233,91]
def f3(item):
n=[int(x) for x in str(item)]
return sum(n)
print(max(nums,key=f3))
'''''''''
# sorted Sort
# sorted( Sequence ) - Compare the size of the elements in the sequence and sort the elements in the sequence from small to large
# sorted( Sequence ,key= function ) - The function determines the size of the comparison object when sorting
# Function requirements :
# a. It's a function
# b. This function has one and only one parameter ( This parameter points to the elements in the sequence )
# c. Function should have a return value ( Comparison object )
'''''''''
# practice 1: Let the elements in the list be sorted from small to large according to the size of single digits
nums=[23,78,80,72,26,91]
def f4(item):
return item%10
print(sorted(nums,key=f4))
'''''''''
# map
'''''''''
Use a : The original sequence -> New sequence
map( function , Sequence ) - Convert the sequence in the specified way , The return value is one map object (map The object is a sequence )
function :a. There is a parameter ( Point to the element in the original sequence ) b. A return value is required ( Elements in the new sequence )
give an example :
nums = [19,78,76,55,30,12]
result = map(lambda item:item%10,nums)
print(list(result))
Use two :
map( function , Sequence 1, Sequence 2) - According to the sequence 1 And sequence 2 Create a new sequence
function :a. There are two parameters , Point to the elements in the sequence respectively b. A return value is required ( Elements in the new sequence )
give an example :
a = [19,78,76,55,30,12]
b = [19,72,72,55,30,12]
result = map(lambda i1,i2:i1+i2,a,b)
print(list(result))
'''''''''
# reduce Accumulate all the data in the sequence
# from functools import reduce Need to import module
'''''''''
reduce( function , Sequence , Initial value )
Function requirements :a. Two parameters are required
The first parameter - Point to the initial value for the first time ; From the second time, it will point to the result of the previous operation
The second parameter - Point to each element in the sequence
b. A return value is required ( Determine the operation rules )
# practice 1: Cumulative sum ?
from functools import reduce
nums = [19,78,76,55,30,12]
result = reduce(lambda x,item:x+item,nums,0)
print(result) # 270
# function (0,19) -> 0+19=19
# function (19,78) -> 19+78=97
# ............
# function (258,12) -> 270
--------------------------------------------
# practice 2: Cumulative multiplication ?
from functools import reduce
nums = [19,78,76,55,30,12]
result = reduce(lambda x,item:x*item,nums,1)
print(result) # 2230113600
----------------------------------------------
# practice 3: Put all the elements in the sequence together ?
# nums = [19,78,76,55,30,12] -> 197876553012
from functools import reduce
nums = [19,78,76,55,30,12]
result = reduce(lambda x,item:x+str(item),nums,'')
print(result) # 197876553012
'''''''''
# 4. No reference decorator
# 1) What is a decorator
'''''''''
effect : Decorators are used to add functions to functions
The essence : It's just a function ( Real argument higher order function + Return value higher order function + Sugar grammar )
usage ( tricks ):
def Function name 1( Parameters 1):
def Function name 2(*args,**kwarg):
Code of new functions
The code that calls the original function : Parameters 1(*args,**kwarg)
return Function name 2
explain :
a. Function name 1 - Name of decorator , More new features to name
b. Parameters 1 - Functions that need to add functions ( Primitive function ), General naming process f、fn
c. Function name 2 - New function name after adding function ,new_f、new_fn
d.
e.
'''''''''
# Add the function of counting the execution time of the function to the function
# Method 1 : Code for adding functions to functions that need to be added
# The problem is : If you add the same function to different functions , The same function needs to be added many times
'''''''''
def func1():
star = time.time()
time.sleep(1)
print(' function 1 The function of ')
end = time.time()
print(' The execution time is :',end-star)
def func2(x,y):
print(x+y)
func1()
func2(10,20)
'''''''''
# Method 2 : Encapsulate the functions to be added into a function
# Existing problems : The original function has no new functions
'''''''''
def func3():
print(' Hello world ')
def count_time(f):
# Get start time
star = time.time()
# Call the original function
time.sleep(1)
f()
# Get the end time
end = time.time()
# Calculate the time difference
print(' The execution time is :',end-star)
count_time(func3)
'''''''''
# Method 3 : Decorator
'''''''''
usage ( tricks ):
def Function name 1( Parameters 1):
def Function name 2():
Code of new functions
The code that calls the original function : Parameters 1()
return Function name 2
explain :
a. Function name 1 - Name of decorator , More new features to name
b. Parameters 1 - Functions that need to add functions ( Primitive function ), General naming process f、fn
c. Function name 2 - New function name after adding function ,new_f、new_fn
def count_time(f):
def new_fn(*args,**kwarg):
start = time.time()
time.sleep(1)
f(*args,**kwarg)
end = time.time()
print(' The execution time is :', end - start)
return new_fn()
@count_time
def func5():
print(' Hello python')
func5 # Hello python The execution time is : 1.0091712474822998
'''''''''
'''''''''
# practice : Write a decorator , Open... When the function starts executing ‘start’
def zz(f):
def new_f(*args,**kwargs):
print('start')
f(*args,**kwargs)
return new_f
@zz
def func6():
print('Hello World')
@zz
def func7(x,y):
print(x+y)
func7(10,20)
func6()
# Output :
start
30
start
Hello World
'''''''''
# 5. There are ornaments for reference
# Application scenarios : If you need additional data to realize the function of decorator , You need a reference decorator
'''''''''
def Function name ( parameter list )
Define parameterless decorator functions
return Parameterless decorator function name
Function name : The name of the function that created the decorator
# Example : Write a reference decorator , Add a label
def create_tag(name):
def tag(f):
def new_f(*args,**kwargs):
result=f(*args,**kwargs)
return f'<{name}>{result}</name>'
return new_f
return tag
@create_tag('a')
def func1():
return 'hello'
print(func1())
'''''''''
More secure sharing , Please pay attention to 【 Security info】 WeChat official account !
copyright notice
author[Wandering mage 12],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/131/202205110607424568.html
The sidebar is recommended
- Introduction to the differences between Python and Java
- Explain Python CONDA in detail
- The pycham downloaded by MAC reports an error as soon as it is opened. The downloaded Python interpreter is also the latest version
- From entry to mastery, python full stack engineers have personally taught Python core technology and practical combat for ten years
- Python is used to detect some problems of word frequency in English text.
- How to choose between excel, database and pandas (Python third-party library)?
- WxPython download has been reporting errors
- Pyside6 UIC and other tools cannot be found in the higher version of pyside6 (QT for Python 6). How to solve it?
- About Python Crawlers
- Successfully imported pandas, unable to use dataframe
guess what you like
How to extract some keywords in the path with Python
Python encountered a problem reading the file!
When Python is packaged into exe, an error is reported when opening assertionerror: C: \ users \ Acer \ appdata \ local \ temp\_ MEI105682\distutils\core. pyc
Eight practical "no code" features of Python
Python meets SQL, so a useful Python third-party library appears
100 Python algorithm super detailed explanation: a hundred dollars and a hundred chickens
[fundamentals of Python] Python code and so on
When Python uses probit regression, the program statement is deleted by mistake, and then it appears_ raise_ linalgerror_ Unrecognized error of singular
Python testing Nicholas theorem
Accelerating parallel computing based on python (BL) 136
Random recommended
- Python dynamic programming (knapsack problem and longest common substring)
- Django uses queryset filter save, and an 'queryset' object has no attribute 'Save' error occurs. Solution?
- Analysis of built-in functions in Python learning
- Python office automation - 90 - file automation management - cleaning up duplicate files and batch modifying file names
- Python office automation - 91 - word file Automation - word operation and reading word files
- After python, go also runs smoothly on the browser
- Self taught Python 26 method
- Summary of Python Tkinter component function examples (code + effect picture) (RadioButton | button | entry | menu | text)
- Python implementation of official selection sorting of Luogu question list
- Application of Django template
- Get project root path and other paths in Python project
- Get, rename, and delete file names in Python projects
- How to set the width and height of Python operation table
- Python string preceded by 'f' R 'B' U '
- JSON and other types convert to each other in Python
- Key value of key combination in pynput in Python
- Conversion of Python PDF file to word file
- Interface testing uses Python decorators
- Get the current time in Python
- Python course notes -- Python string, detailed explanation of related functions
- Python file and folder operations
- Python file content operation
- Three basic data quality evaluation methods and python implementation
- Python data structure and mathematical algorithm examples (continuously updating)
- GUI interface mail sending program based on SMTP protocol server and python language
- Python application tool development: mail sending GUI program
- Python application tool development: PIP instruction GUI program
- Application development based on Python and MySQL database: student information score management system version 1.0
- [Python] sort and sorted
- [Python] create a two-dimensional array with list, which is easy to step on
- Multiply [email protected]
- About creating in Python project folder__ init__. Understanding of PY
- Python, zsbd
- Smplify introduction and in python2 7 operation in environment
- Boost(2):boost. Python library introduction and simple examples
- Boost (3): encapsulate C + + classes into Python classes
- Boost (5): extract the type of C + + language and extract class from Python object
- Boost(6):Boost. How Python converts C + + parameter and return value types
- Boost(7):Boost. Python encapsulates overloaded functions and passes default parameters
- Boost(8):Boost. Python implements Python objects and various types of built-in operations and methods