程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python foundation] generating formula, decorator, high-order function

編輯:Python

Generative 、 Decorator 、 Higher order function

  • One 、 Generative
    • (1)、 List generator
    • (2)、 Set generative
    • (3)、 Dictionary generative
  • Two 、 generator
    • (1)、 Generator features
    • (2)、 Usage method
  • 3、 ... and 、 Closure
    • (1)、 Understand timestamps
    • (2)、 Closure
  • Four 、 Decorator
    • (1)、 Decorator
    • (2)、 Decorator with parameters
    • (3)、 Multiple decorators
  • 5、 ... and 、 Built in higher order function
    • (1)、map function
    • (2)、reduce function
    • (3)、filter function
    • (4)、sorted function

One 、 Generative

(1)、 List generator

A list generator is an expression used to generate a list in a specific syntax form . yes Python Provides a concise form of generating lists , Can quickly generate a new list.
1、 Usage method

 Common grammar :[exp for iter_var in iterable]
Syntax format with filter function : [exp for iter_var in iterable if_exp]
Syntax format with filter function : [exp for iter_var in iterable if_exp]

2、 Basic application
It can transform tedious methods 1 Simplify to method 2

Method 1

import string
import random
codes = []
for count in range (100): # loop 100 Time , Every time it is generated arbitrarily 4 A string 
code = "".join(random.sample(string.ascii_letters,4))
codes.append(code)
print(codes)
# result 
['MIFp', 'zJct', 'KpNB', 'afcS', 'zCnv', 'nzgH', 'IlhR', 'UHJk', ....

Method 2

codes = [ "".join(random.sample(string.ascii_letters,4)) for i in range(100)]
print(codes)
# result 
['mnLM', 'LVKe', 'ntlM', 'BjYl', 'KIAt', 'gRBl', 'QiqH', ...

3、 Exercises
find 1 To 100 It can be 3 Divisible number
Method 1

nums = []
for num in range(1,100):
if num % 3 == 0:
nums.append(num)
print(nums)

Method 2
Using the formula generator

nums = [num for num in range(1,100) if num % 3 == 0]
print(nums)

(2)、 Set generative

The set generation formula is as follows

result = {
i**2 for i in range(10)}
print(result)
# result 
{
0, 1, 64, 4, 36, 9, 16, 49, 81, 25}

(3)、 Dictionary generative

The dictionary generation formula is as follows

result={
i:i**2 for i in range(10)}
print(result)
# result 
{
0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

Two 、 generator

(1)、 Generator features

stay python The mechanism of loop and compute in is called generator

Use scenarios

(2)、 Usage method

1、 Generator method
Method 1: The first way to implement ( Rewrite the generative expression into a generator )

nums = (i**2 for i in range(1000))
print(nums)
# result 
<generator object <genexpr> at 0x0000018FFF234900>

The above is not convenient to view , You can view the values in the following way

nums = (i**2 for i in range(1000))
for num in nums:
print(num)
# result 
0
1
4
9
16
25
36
...

Method 2:yield keyword

 return: Function encountered return Just go back to , The following functions will not execute .
yield: encounter yield Then stop executing the code , Call again next When the method is used , Since the last stop yiled Continue to the next yield
def login():
print('step1') # step
yield 1 #output
print('step')
yield 2
print('step 3')
yield 3
# If there is in the function yield keyword , The return value of the function is a generator 
g = login()
print(next(g))
print(next(g))

3、 ... and 、 Closure

(1)、 Understand timestamps

import time
start_time=time.time() # from 1970.1.1 The number of seconds to now 
time.sleep(2) # Sleep for two seconds 
end_time = time.time() # from 1970.1.1 The number of seconds to now 
print(end_time-start_time)
# result 
2.00744891166687

(2)、 Closure

1、 Functions are nested inside functions
2、 The return value of an external function is a reference to an internal function
3、 Internal functions can use variables of external functions

import time
def timeit(name):
def wrapper():
print('wrapper'+name)
print('timeit')
return wrapper
in_fun = timeit(name = 'westos') in_fun At this time, it is equivalent to wrapper function
in_fun() It is equivalent to calling internal and external functions at the same time

Four 、 Decorator

(1)、 Decorator

1、 Basic template

import time
from functools import wraps
def Name of decorator (f):
@wraps(f) Keep the help documentation for the decorator function
def wrapper(*args,**kwargs):
# Here you can add things before executing the function 
result=f(*args,**kargs)
# What you do after executing the function 
return result Return the function to the decorated function
return wrapper()

2、 give an example

# Decorator : Functions used to decorate functions 
# Without changing the source code , Tools to add additional functionality 
# Using closures to implement decorators 
import time
def timeit(f):
def wrapper(x,y):
start = time.time()
result= f(x,y) # Execution is add(x,y)
end = time.time()
print(' The function runs for :%.4f'%(end-start))
return result
return wrapper
@timeit # Decorative sugar , The time here will be add Function to timeit(add())
def add(x,y):
return x+y
result = add(1,3)
print(result)

3、 add to wraps, Help documents of functions can be described separately

# Decorator : Functions used to decorate functions 
# Without changing the source code , Tools to add additional functionality 
# Using closures to implement decorators 
import time
from functools import wraps
def timeit(f):
"""" The decorator of the timer """
@wraps(f) # Keep the attribute information and help documents of the decorated function 
def wrapper(*args,**kwargs):
start = time.time()
result= f() # Execution is login()
end = time.time()
print(' The function runs for :%.4f'%(end-start))
return result
return wrapper
@timeit # Decorative sugar , The time here will be add Function to timeit(add())
def login():
""""login Help document for """
print('login')
print(help(timeit))

(2)、 Decorator with parameters

import time
from functools import wraps
def timeit(args='seconds'):
def desc(f):
"""" The decorator of the timer """
@wraps(f) Keep the attribute information and help documents of the decorated function
def wrapper(*args,**kwargs):
start = time.time()
result= f() Execution is login()
end = time.time()
if args =='seconds':
print(f" function {
f.__name__} The running time is {
end-start} second ")
elif args == 'mintues':
print(f" function {
f.__name__} The running time is {
(end - start)/60} second ")
return result
return wrapper
return desc
@timeit(args='mintues') To achieve timeit() It will @ perform desc function , namely desc=desc(login)
def login():
""""login Help document for """
print('login')
login()

(3)、 Multiple decorators

Note that the decorator is called from bottom to top , Call the second decorator first is_permisson, Then call the first decorator is_login, But the end result is from top to bottom , Output the result of a decorator , Then output the result of the second decorator , Finally, the result of executing the function .

from functools import wraps
def is_login(f):
@wraps(f)
def wrapper1(*args,**kwargs):
print('is_login, Is the user logged in ')
result=f(*args,**kwargs)
return result
return wrapper1
def is_permisson(f):
@wraps(f)
def wrapper2(*args,**kwargs):
print('is_permission, Whether the user has permission ')
result=f(*args,**kwargs)
return result
return wrapper2
@is_login
@is_permisson Note that the decorator is called from bottom to top , First call is_permisson, Call again is_login
def show_hosts():
print(' Display all virtual machines ')
show_hosts()

The specific calling sequence is as follows

1、is_permisson The module calls first
First show_host=is_permisson(show_hosts)
Get the results show_host=wrapper2

2、is_login The module is called again
show_hosts = is_login(wrapper2) ( Because the last decorator made show_hosts by wrapper2, So the function passed in here is wrapper2)
Get the results show_hosts=wrapper1

3、 The above two steps are finished , Carry out the third step show_hosts function .
Now? show_hosts Function time wrapper1, So execute show_hosts The function actually executes wrapper1 function , Output is :
’is_login, Is the user logged in ‘
And then execute f(*args,**kwargs), Follow the steps 2 It is found that the function passed in is wrapper2, So execute wrapper2 function , Output is :
‘is_permission, Whether the user has permission ’
Finally, execute f(*args,**kwargs), Follow the steps 1 It is found that the function passed in is show_hosts, So execute show_hosts Self function , Output is :
‘ Display all virtual machines ’

5、 ... and 、 Built in higher order function

(1)、map function

Processing in parallel at the same time

# Calculation x Of 2 Power 
result = map(lambda x:x**2,[1,2,3,4])
print(list(result))
# result 
[1, 4, 9, 16]
result=map(lambda x,y:x+y,[1,2,3],[4,5,6])
print(list(result))
# result 
[5, 7, 9]

(2)、reduce function

Take the result of the former as the input of the latter

# reduce function 
# Calculation ((2**3)**3)=reduce result
from functools import reduce
result = reduce(lambda x, y: x**y, [2, 3, 3])
print(result)

practice ·: Calculation 1×2×...100

from functools import reduce
result = reduce(lambda x,y: x * y,list(range(1,100))) Be sure to convert to a list
print(result)

(3)、filter function

Filter function
Filter out even numbers

result=filter(lambda x:x % 2==0,[1,2,4,5])
print(list(result))
# result 
# filter function 
result=filter(lambda x:x % 2==0,[1,2,4,5])
print(list(result)) Output as list

(4)、sorted function

Sort numbers by size , From small to large

result = sorted([1,4,321,2])
print(result)
result = sorted([1,4,321,2],reverse=True)
print(result)
# result 
[321, 4, 2, 1]

According to whether the number is 0 Sort
The rule in the function is to set non - 01 Is endowed with 1, And then according to 0 ,1 Sort , Return the real value after sorting

result = sorted([1,4,0,2],key=lambda x:0 if x==0 else 1)
print(result)
[0, 1, 4, 2]

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved