当前位置:网站首页>Ternary expressions, generative expressions, anonymous functions

Ternary expressions, generative expressions, anonymous functions

2022-07-07 21:48:00 zxr1002

Yesterday's review

Decorator : Add new functions without changing the original invocation method and internal code decorated

Multi layer decorator :

def outter1(func1):  # func1 be equal to wrapper2
    print(' To load the outter1')
    def wrapper1(*args, **kwargs):
        print(' Yes wrapper1')
        res1 = func1(*args, **kwargs)
        return res1
    return wrapper1

def outter2(func2):  # func2 be equal to wrapper3
    print(' To load the outter2')
    def wrapper2(*args, **kwargs):
        print(' Yes wrapper2')
        res2 = func2(*args, **kwargs)
        return res2
    return wrapper2

def outter3(func3):  # func3 Equal to real index function 
    print(' To load the outter3')
    def wrapper3(*args, **kwargs):
        print(' Yes wrapper3')
        res3 = func3(*args, **kwargs)
        return res3
    return wrapper3
@outer1
@outer2
@outer3
def index():
    pass
'''
 When there is multi-layer grammar sugar , Execution is from bottom to top , Close to the function name, start to execute 
'''

There are ornaments for reference :

​ If you pass in parameters in an outer function, you cannot , Only function names can be passed in there , After passing in parameters, the syntax sugar cannot be executed

​ It is also impossible to pass parameters into inner functions , Changed the original condition of the decorator

​ resolvent : Add a layer of functions on the outside , You can pass in multiple values , The return value is set to the function name of the next level , Then there is the normal decorator

def outer(condition,type_user):
    def login_auth(func_name):  #  No other formal parameters can be filled here 
        def inner(*args, **kwargs):  #  You can no longer fill in the parameters required by non decorated objects 
            username = input('username>>>:').strip()
            password = input('password>>>:').strip()
            #  Different codes should be executed according to the needs of users 
            if type_user =='jason':print('VIP')
            if condition == ' list ':
                print(' Use lists as data sources ')
            elif condition == ' Dictionaries ':
                print(' Use dictionaries as data sources ')
            elif condition == ' file ':
                print(' Use files as data sources ')
            else:
                print(' At present, there are only the above ways ')
        return inner
    return login_auth
@outer(' file ','jason')  #  Parenthesized function name execution priority    @login_auth
def index():
    print('from index')
index()

Recursive method :

​ One layer is simpler than another , There must be an end condition

​ recursive : Look down for the answer layer by layer

​ to flash back : Deduce the result according to the known conditions

Algorithm -- Dichotomy :

​ Algorithm : Solutions to problems

​ Compare the half score with the target number , If the target number is large, it will be in the second half , If the target number is small, it is in the first half , And then compare the size in half

​ The disadvantage is that if the objective function is found by dichotomy at the beginning or end, the efficiency will be low , It must be an ordered sequence

Content learning today

Ternary expression

characteristic : You can reduce the number of lines of code

Grammatical structure :

 value 1 if  Conditions  else  value 2

​ It can be understood as :

 Result when condition is true  if  Conditions  else  Result when condition is false 

Limit : It is only limited to one of two cases and nesting is not recommended

Example show :

#  Compare the size of two numbers 
num1 = input('num1:')
num2 = input('num2:')
if num1 > num2:
    return num1
else:
    return num2
#  Function to write the size of two numbers 
def num_max(num1, num2):
    if num1 > num2:
        return num1
    else:
        return num2
res = num_max(12, 13)
print(res)  # 13
#  Using the ternary expression 
def num_max(num1, num2):
    return num1 if num1 > num2 else num2
res = num_max(12, 13)
print(res)  # 13

print('haha' if 0 else 'heihei')
print('huhu' if 1 else 'gaga')
'''
heihei
huhu
'''
#  Ternary expressions can be used more than just between numbers 

Various generative

1. List generator

#  Add _nb
l1 = ['aa', 'bb', 'cc', 'dd', 'ee']
# #  According to the knowledge we have learned, we can use for Loop to achieve 
# # 1. Define a new list first 
new_list = []
# # 2. Cycle all data values in the original list , Use for loop 
for name in l1:
#     # 3.name It's the name that comes out of each cycle , Add suffixes to each name 
   new_name = name + '_nb'
#     # 4. Use the built-in method of list after splicing append, Append to the empty list 
   new_list.append(new_name)
print(new_list)  # ['aa_nb', 'bb_nb', 'cc_nb', 'dd_nb', 'ee_nb']
#  Use list generation 
l1 = ['aa', 'bb', 'cc', 'dd', 'ee']
new_list = [name + '_nb' for name in l1]
print(new_list)  # ['aa_nb', 'bb_nb', 'cc_nb', 'dd_nb', 'ee_nb']
image-20220707155211908
#  List generation support if Judge ( Only for、if)
l1 = ['aa', 'bb', 'cc', 'dd', 'ee']
new_list = [name + '_nb' for name in l1 if name != 'aa']
'''
1. The first thing to execute is for loop 
2.for The data value obtained by circulation enters if The judgment of the , If the condition is true, the previous splicing operation will be performed , If not, discard the data value directly 
3. After judgment name + '_nb' The operation of 
4. Then put it into this list by default 
'''
image-20220707160314600

2. Dictionary generative

#  Dictionary generative 
d1 = ['aa', 'bb', 'cc', 'dd', 'ee']
new_dict = {i:'jason' for i in range(5)}
print(new_dict)  # {0: 'jason', 1: 'jason', 2: 'jason', 3: 'jason', 4: 'jason'}
'''
1. First, execute for loop 
2. Check whether there is if Conditions , If there is any, execute if Conditions , If not, look at the previous execution statement 
3. And then i The values of are placed in the previous statements in turn 
4. Because the whole outside use {} The parcel , So directly output a pair of key value pairs in the form of a dictionary 
'''
#  Dictionary generation plus if sentence 
d1 = ['aa', 'bb', 'cc', 'dd', 'ee']
new_dict = {i:'jason' for i in range(5) if i == 4}
print(new_dict)  # {4: 'jason'}
'''
 The print result is a key value pair , according to if Conditions for printing 
'''

3. Set generative

# Set generative 
new_set = {i for i in range(10)}
print(new_set)  # {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
new_set = {i for i in range(10) if i == 6}
print(new_set)  # {6}
'''
1. It is also the first to execute for loop , If not at the back if The statement is just the previous statement 
2. Put the data values from the loop into the previous statement one by one , Then the output 
3. Outside is {} Wrapped in direct output is set 
'''

Be careful : Tuple has no generator

Anonymous functions

1. It can be understood as a function without a function name

2. keyword :lambda

3. expression :lambda Parameters :return Return value

​ Anonymous function can be regarded as an expression , It just has to have a return value

4. advantage : The process of defining functions can be omitted , Combined with some built-in functions

​ It can become a famous function

​ Reduce code , Is the code more concise

5. The application case (max,min,sorted,map,reduce,filter)

Anonymous collection built-in functions use

#  Common built-in functions 
# 1.max()---- For maximum 
l1 = [1, 2, 3, 4, 6, 8, 10, 35, 67, 34, 76, 90, 15, 38, 29]
res = max(l1)
#  If it is in the dictionary v The maximum value of ??
d1 = {'zz': 199, 'ss': 67, 'dd': 3456, 'xx': 12345}
res = max(d1, key=lambda k: d1.get(k))
print(res)  # xx
'''
1.max The bottom is for loop 
2. If there is no back key value , Get is k key , Then it is to compare directly , Usually it's a string , Then string comparison is usually the first , Compare sizes by encoding 
3. If there is key value ,for Cycle to get k value , then k Value is passed as a parameter to lambda Parameters in , Then the return value passes get Way to get v value , At this point, the return value is v value , Then take v Value comparison 
4. The last output is the name , It's because for What circulates out is k value , The final result is still according to for Circularly 
'''
#  If anonymous functions cannot be used , Then use the function 
def index(k):
    return d1.get(k)
res = max(d1,key=index)
print(res)  # xx
''' It should be noted that index There can only be one formal parameter , because max At the bottom is a for The loop can only take one value at a time '''
# # 2.min()---- For the minimum 
res1 = min(l1)  # 1
print(res1)  # 90

Important built-in functions

# 1.map()---- mapping 
l1 = [1, 2, 3, 4, 6, 8, 10, 35, 67, 34, 76, 90, 15, 38, 29]
res = map(lambda x: x + 20, l1)
print(list(res))  # [21, 22, 23, 24, 26, 28, 30, 55, 87, 54, 96, 110, 35, 58, 49]
'''
1. The bottom one is for loop ,
2. Take out the values in the list one by one 
3. Each time the extracted function is given to the formal parameters of the function 
4. Then pass it to the return value to get the result 
'''
#  Custom function 
def index(a):
    return a + 20
res = map(index, l1)
print(list(res))

# 2.filter()---- Filter out the elements that do not meet the conditions , Return qualified elements 
l1 = [1, 2, 3, 4, 6, 8, 10, 29]
res = filter(lambda a: a != 3, l1)
print(list(res))  # [1, 2, 4, 6, 8, 10, 29]
#  Custom function 
def index(a):
    return a != 3
res = filter(index,l1)
print(list(res))  # [1, 2, 4, 6, 8, 10, 29]

# 3.reduce()--- It is associated with map() The difference is that it needs to pass in two values 
from functools import reduce
l2 = [1,4,5,7]
res_l2 = reduce(lambda x, y: x + y,l2,100)
print(res_l2)  # 17
'''
1. Turn many monomers into a whole ,
2. Two parameters should be given at one time , The first value is two values , Then it's time to take one , The other one is the last return value 
3. You can also transfer values later , This value is added after the execution in the list 
'''
# 4.zip()
n1 = [1,2,3]
n2 = ['jason','kevin','oscar']
res = zip(n1,n2)
print(list(res))  # [(1, 'jason'), (2, 'kevin'), (3, 'oscar')]
'''
1. Multiple values can be spliced 
2. The splicing value should support for loop 
3. If the stored data is of different lengths , Then connect according to the shortest one 
'''

Homework

Everyone will describe the implementation process of multi-layer decorators and participatory decorators in words

1. Multi layer decorator

def outter1(func1):  # func1 be equal to wrapper2
    print(' To load the outter1')
    def wrapper1(*args, **kwargs):
        print(' Yes wrapper1')
        res1 = func1(*args, **kwargs)
        return res1
    return wrapper1

def outter2(func2):  # func2 be equal to wrapper3
    print(' To load the outter2')
    def wrapper2(*args, **kwargs):
        print(' Yes wrapper2')
        res2 = func2(*args, **kwargs)
        return res2
    return wrapper2

def outter3(func3):  # func3 Equal to real index function 
    print(' To load the outter3')
    def wrapper3(*args, **kwargs):
        print(' Yes wrapper3')
        res3 = func3(*args, **kwargs)
        return res3
    return wrapper3
@outter1
@outter2
@outter3
def index():
    print('from index')
index()
'''
1. When there are multiple grammatical sugars , First look at the syntax sugar closest to the function , Syntax sugar does not assign the name of the function name that is the same as the true function until the last time , Otherwise, it depends on its return value, which is regarded as the name of the assignment 
2. The function of syntax sugar is to pass the next function name as a parameter to @ The following function 
    2.1 outter3(index)( Parenthesized function names have the highest execution priority , It starts first , And then we did  【print(' To load the outter3')】, Then execute the function wrapper3, Re execution return wrapper3)-->wrapper3 =outter3(index)
    2.2 wrapper3 It is a function name that triggers @outter2, Then follow the above operation ,( Parenthesized function names have the highest execution priority , It starts first , And then we did  【print(' To load the outter2')】, Then execute the function wrapper2, Re execution return wrapper2)-->wrapper2 =outter2(wrapper3)
    2.3 wrapper2 Triggered @outter1,.......-->index =outter1(wrapper2)
3. call index() The implementation process of , here index yes wrapper1, Now it's actually wrapper1(),
    wrapper1 The function starts executing -->【 print(' Yes wrapper1')】,res1 = func1(*args, **kwargs),func1 Now it's wrapper2,return res1 That's it wrapper2
    wrapper2 The function starts executing -->【 print(' Yes wrapper2')】,res2 = func2(*args, **kwargs),func2 Now it's wrapper3,return res2 That's it wrapper3
    wrapper3 The function starts executing -->【 print(' Yes wrapper3')】,res3 = func3(*args, **kwargs),func3 Now it's index,return res3 That's it print('from index')
4. Summarize the execution process :
	 When the multi-layer decorator is executed from the bottom up, the syntax sugar is executed first according to the trigger conditions of the syntax sugar and function name , Execute the outer functions one by one from top to bottom, and finally return to the real function name at the beginning ( The real function name is not the same as the real function name ) When , Then start executing internal functions from top to bottom , Finally return to the function to be executed , printout .
'''

2. There are ornaments for reference

def outer(condition,type_user):
    def login_auth(func_name):  #  No other formal parameters can be filled here 
        def inner(*args, **kwargs):  #  You can no longer fill in the parameters required by non decorated objects 
            username = input('username>>>:').strip()
            password = input('password>>>:').strip()
            #  Different codes should be executed according to the needs of users 
            if type_user =='jason':print('VIP')
            if condition == ' list ':
                print(' Use lists as data sources ')
            elif condition == ' Dictionaries ':
                print(' Use dictionaries as data sources ')
            elif condition == ' file ':
                print(' Use files as data sources ')
            else:
                print(' At present, there are only the above ways ')
        return inner
    return login_auth
@outer(' file ','jason')  #  Parenthesized function name execution priority    @login_auth
def index():
    print('from index')
index()

'''
 Executive summary :
1. Add formal parameters to external functions , Then you have to add parameters to the grammar sugar , But if you add parameters to the grammar sugar , The interpreter automatically recognizes the function name plus () Execution priority , Then the grammar sugar will not be executed , External function brackets can only be used to receive decorated function names 
2. Add formal parameters to internal functions , Then you must pass in a parameter when executing the internal function , But passing in parameters does not conform to the decorator's principle. The original function does not need to pass in parameters when executing , But now we need , Therefore, this method cannot 
3. So we can only use closure function to solve , Set a function on the outermost , Set the parameters to be passed in as formal parameters , The return value is the original outer function , Then at this time, there is a complete decorator inside , Did not destroy it , At the same time, this additional function can pass in multiple values 
'''
原网站

版权声明
本文为[zxr1002]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207072018061317.html