当前位置:网站首页>Advanced order of function
Advanced order of function
2022-07-04 10:38:00 【She was your flaw】
Advanced functions
One 、 Anonymous functions
‘’’
- Anonymous functions
grammar :
Function name = lambda parameter list : Return value
amount to :
def Function name ( parameter list ):
return Return value
Be careful :
1) Anonymous functions can only implement functions that can complete functions in one sentence of code
2) Anonymous functions are no different from ordinary functions when called
3) Parameters of anonymous functions cannot use colon syntax to describe types
‘’’
sum1 = lambda num1, num2=10: num1 + num2
print(sum1(10, 20)) # 30
print(sum1(num1=100, num2=200)) # 300
print(sum1(5)) # 15
# practice : Define an anonymous function to obtain a specified number of single digits
count1 = lambda num1: num1 % 10
print(count1(23876)) # 6
Two 、 Variable scope
‘’’
Variable scope – It refers to the range of variables that can be used
According to the different scope of variables, variables are divided into : Global and local variablesGlobal variables
Variables that are not defined in functions or classes are global variables ;
The scope of global variables is from the beginning of definition to the end of the program .local variable
The variables defined in the function are local variables ( Formal parameters are also local variables );
The scope of a local variable is from the beginning of the definition to the end of the function .Function call procedure ( Memory changes )
Every time you call a function , The system will automatically open up a temporary memory area for this function in the stack , Used to store local variables defined in functions .
When the function call ends, the system will automatically release this memory .
‘’’
# a、b、c It's all global variables
a = 100
for b in range(10):
print(b)
c = 20
print(f' Use in circulation a:{
a}')
print(f' Recycle outside b and c:{
b}, {
c}')
def func1():
print(f' Use in a function a、b、c:{
a}, {
b}, {
c}')
func1()
"""2. local variable """
def func2(x):
y = 100
for z in range(10):
pass
print(' End of the function ')
print(f' The function uses x, y, z:{
x}, {
y}, {
z}')
‘’’
4. global and nonlocal – Can only be used in the body of a function
global - 1) Modify the value of the global variable in the function , It needs to be in the front global Describe the variables ;
2) Define a global variable in the function , It needs to be used in the front global Describe the variables .
global Variable name
( understand )nonlocal - If you need to modify the value of a local variable locally
‘’’
m = 100
n = 100
def func3():
# Global variables are not modified here m Value , Instead, redefine a new local variable m
m = 200
global n
n = 200
# You can use global variables in functions
print(f' Function m:{
m}')
print(f' Function n:{
n}')
global x
x = 'abc'
func3()
print(f' Outside the function m:{
m}')
print(f' Outside the function n:{
n}')
print(f' Outside the function x:{
x}')
ab = 100
def func4():
xy = 200
print(f'func4:{
ab}, {
xy}')
def func5():
nonlocal xy
xy = 300
print(f'func5:{
ab}, {
xy}')
func5()
print(f'func4-xy:{
xy}')
func4()
3、 ... and 、 Functions are variables
‘’’
1. Important conclusions
python To define a function in is to define the type function The variable of , A function name is a variable name
‘’’
func1 = lambda x: x*2
print(type(func1)) # <class 'function'>
“”"
Equivalent to :
def func1(x):
return x*2
“”"
def func2():
print(' function !')
a = 10
print(type(a)) # <class 'int'>
print(type(func2)) # <class 'function'>
print(id(a))
print(id(func2))
b = a
print(b + 10)
c = func2
c()
list1 = [a, 100]
list2 = [func2, 100, func2()]
print(list2)
a = 'abc'
func2 = 'abc'
1. Variables as arguments to functions
def func3(x):
print(f'x:{
x}')
def func4():
print(' function 4')
func3(199)
num = 200
func3(num)
func3(func4)
1)x Can pass numbers 、 character string 、 list 、 Tuples
def func5(x):
print(x * 2)
2)x You can pass strings 、 list 、 Tuples 、 Dictionaries
def func6(x):
print(x[0])
3)x Can only be sent to list
def func7(x):
x.append(100)
print(x)
4)func8 and func9 Is a higher-order function with real parameters - Because there are functions in the parameters of these two functions
x Can only pass functions , And this function can be called without passing parameters
def func8(x):
print(x())
5)x Can only pass functions ; When calling a function, you can accept only one parameter ; The return value must be a number
def func9(x):
print(x(10) / 2)
func10 Is a higher-order function of return value - because func10 The return value of is a function
def func10():
def func11():
print('hello')
return 100
return func11
print(func11()) => print(100)
print(func10()())
Four 、 Common real parameter higher-order functions
- Common real parameter higher-order functions
max、min、sorted/sort
map
reduce
(1) max、min、sorted
max( Sequence , key= function )
Function requirements : a. There is and only one parameter ( This parameter points to each element in the previous sequence )
b. There is a return value ( The return value is the comparison object )
nums = [89, 78, 98, 23, 67, 81]
print(max(nums))
a. seek nums The element with the largest median bit :89
nums = [89, 78, 98, 23, 67, 81]
Method 1 :
def temp(item):
return item % 10
print(max(nums, key=temp))
Method 2
print(max(nums, key=lambda item: item % 10))
b. seek nums The element with the largest median ( Treat strings as numbers ): 100
nums = [89, '100', 34, '78', 90]
print(max(nums, key=lambda item: int(item)))
c. Get the information of the oldest student ; Get information about the students with the lowest grades
students = [
{
'name': ' Xiao Ming ', 'age': 18, 'score': 90},
{
'name': ' Lao Wang ', 'age': 28, 'score': 67},
{
'name': ' Zhang San ', 'age': 22, 'score': 83},
{
'name': ' Li Si ', 'age': 25, 'score': 57}
]
print(max(students, key=lambda item: item['age']))
print(min(students, key=lambda item: item['score']))
d. obtain nums The sum of each digit and the largest element
nums = [123, 34, 45, 97, 209, 83]
for example [6, 16, 11, 10, 10]
def temp(item):
s = 0
for x in str(item):
s += int(x)
return s
print(max(nums, key=temp))
print(sorted(nums, key=temp))
5、 ... and 、map and reduce
‘’’
- map
1)map( function , Sequence ) - Transform all elements in the sequence according to the specified rules to produce a new sequence
Function requirements :a. There is a parameter ( Point to the elements in the sequence )
b. A return value is required ( Elements in the new sequence , Describe the relationship between the new sequence element and the original sequence element )
- map( function , Sequence 1, Sequence 2)
Function requirements :a. There are two parameters , The first parameter points to the sequence 1 The elements in , The second parameter points to the sequence 2 Medium element
b. A return value is required ( Elements in the new sequence , Describe the relationship between the new sequence element and the original sequence element )
Function can be followed by N A sequence of , Ask for this N The number of elements in a sequence must be the same ; How many sequences , How many parameters does the function need
‘’’
‘’’
[23, 45, 78, 91, 56] -> [‘23’, ‘45’, ‘78’, ‘91’, ‘56’]
[23, 45, 78, 91, 56] -> [3, 5, 8, 1, 6]
‘’’
nums = [23, 45, 78, 91, 56]
print(list(map(lambda item: str(item), nums)))
print(list(map(lambda item: item % 10, nums)))
nums1 = [1, 2, 3, 4, 5]
nums2 = [6, 7, 8, 9, 1]
""" [16, 27, 38, 49, 51] """
result = map(lambda i1, i2: i1 * 10 + i2, nums1, nums2)
print(list(result))
practice 1:
names = [' Xiao Ming ', ' Zhang San ', ' Li Si ', ' Lao Wang ']
ages = [18, 30, 26, 35]
[
{
'name': ' Xiao Ming ', 'age': 18},
{
'name': ' Zhang San ', 'age': 30},
...
]
print(list(map(lambda x, y: {
'name': x, 'age': y}, names, ages)))
‘’’
2. reduce
reduce( function , Sequence , Initial value )
function :a. There are and only two parameters
The first parameter : Point to the initial value for the first time , The second start points to the result of the previous operation ( It can be directly regarded as the initial value )
The second parameter : Point to each element in the sequence
b. Return value : Describe the merge rule ( Use initial values and elements to describe )
‘’’
“”"
[1, 2, 3, 4, 5] -> 15 (1+2+3+4+5) Initial value 0
[1, 2, 3, 4, 5] -> 120 (12345) Initial value 1
[1, 2, 3, 4, 5] -> ‘12345’ (’’ + ‘1’+‘2’+‘3’+‘4’+‘5’) Initial value ‘’
“”"
from functools import reduce
nums = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x+y, nums, 0)
print(result)
result = reduce(lambda x, y: x * y, nums, 1)
print(result)
result = reduce(lambda x, y: x+str(y), nums, '')
print(result)
practice 2:
students = [
{
'name': ' Xiao Ming ', 'age': 18, 'score': 90},
{
'name': ' Lao Wang ', 'age': 28, 'score': 67},
{
'name': ' Zhang San ', 'age': 22, 'score': 83},
{
'name': ' Li Si ', 'age': 25, 'score': 57}
]
''' demand 1:' Xiao Ming, Lao Wang, Zhang San, Li Si ' '' + ' Xiao Ming ' + ' Lao Wang ' + ' Zhang San ' + ... demand 2:[' Xiao Ming ', ' Lao Wang ', ' Zhang San ', ' Li Si '] [] + [' Xiao Ming '] + [' Lao Wang '] + ... '''
result = reduce(lambda x, y: x + y['name'], students, '')
print(result)
result = reduce(lambda x, y: x + [y['name']], students, [])
print(result)
Homework
Already list points The coordinates of each point are saved in ( Coordinates are represented by tuples , The first value is x coordinate , The second value is y coordinate )
points = [ (10, 20), (0, 100), (20, 30), (-10, 20), (30, -100) ]
The following problems are solved by using real parameter higher-order functions
1) Get the list of y The point with the largest coordinate
result = max(points, key=lambda y: y[1]) print(result) # (0, 100)
2) Get the list of x The point with the smallest coordinates
print(min(points, key=lambda x: x[0]))
3) Get the point furthest from the origin in the list
print(max(points, key=lambda x: (x[0] ** 2 + x[1] ** 2)))
4) Point by point to x The distance of the axis is sorted from large to small
print(sorted(points, key=lambda x: x[1] ** 2, reverse=True))
Ask for a list nums The element with the largest absolute value in
nums = [89, -78, -90, 23, -67, 81] print(max(nums, key=lambda item: (item * item) ** 2)) # -90
There are already two lists A and B, use map Function to create a dictionary ,A The element in is key,B The element in is value
A = ['name', 'age', 'sex'] B = [' Zhang San ', 18, ' Woman '] New dictionary : { 'name': ' Zhang San ', 'age': 18, 'sex': ' Woman '}
print(dict(map(lambda i1, i2: (i1, i2), A, B)))
There are three lists representing 5 The names of the students 、 Discipline and class number , Use map Put the three lists together into a dictionary that represents the class information of each student
names = [' Xiao Ming ', ' floret ', ' Xiaohong ', ' Lao Wang '] nums = ['1906', '1807', '2001', '2004'] subjects = ['python', 'h5', 'java', 'python'] result :{ ' Xiao Ming ': 'python1906', ' floret ': 'h51807', ' Xiaohong ': 'java2001', ' Lao Wang ': 'python2004'}
result = map(lambda name1, num1, subject1: (name1, subject1 + num1), names, nums, subjects) print(dict(result))
Already a list message, Use reduce Calculate the sum of all numbers in the list ( Use list derivation and no list derivation to do )
message = [' Hello ', 20, '30', 5, 6.89, 'hello'] result :31.89
result = reduce(lambda x, y: x+y, [x for x in message if type(x) in (int, float)], 0) print(result)
6. It is known that a dictionary list stores the grades of each student in each subject ,
students = [
{
'name': 'stu1', 'math': 97, 'English': 67, 'Chinese': 80},
{
'name': 'stu2', 'math': 56, 'English': 84, 'Chinese': 74},
{
'name': 'stu3', 'math': 92, 'English': 83, 'Chinese': 78},
{
'name': 'stu4', 'math': 62, 'English': 90, 'Chinese': 88}
]
1. Calculate and add the average score of each student
def new_students(item):
item['avg'] = (item['math']+item['English']+item['Chinese']) // 3
return item
students1 = list(map(new_students, students))
print(students1)
2. Sort according to the average score from high to low
result = sorted(students1, key=lambda x: x['avg'], reverse=True)
print(result)
边栏推荐
- Service developers publish services based on EDAs
- Write a program to define an array with 10 int elements, and take its position in the array as the initial value of each element.
- Dichotomy search (C language)
- The time difference between the past time and the present time of uniapp processing, such as just, a few minutes ago, a few hours ago, a few months ago
- Hlk-w801wifi connection
- 【FAQ】华为帐号服务报错 907135701的常见原因总结和解决方法
- [FAQ] summary of common causes and solutions of Huawei account service error 907135701
- [test theory] test process management
- [Galaxy Kirin V10] [server] system startup failed
- Three schemes of ZK double machine room
猜你喜欢
[Galaxy Kirin V10] [desktop] printer
[Galaxy Kirin V10] [server] NFS setup
Remove linked list elements
[FAQ] summary of common causes and solutions of Huawei account service error 907135701
Vs201 solution to failure to open source file HPP (or link library file)
When I forget how to write SQL, I
Network connection (II) three handshakes, four waves, socket essence, packaging of network packets, TCP header, IP header, ACK confirmation, sliding window, results of network packets, working mode of
Sword finger offer 05 (implemented in C language)
BGP advanced experiment
Safety reinforcement learning based on linear function approximation safe RL with linear function approximation translation 1
随机推荐
Uniapp--- initial use of websocket (long link implementation)
Using SA token to solve websocket handshake authentication
Es advanced series - 1 JVM memory allocation
Write a program to judge whether the two arrays are equal, and then write a similar program to compare the two vectors.
Software sharing: the best PDF document conversion tool and PDF Suite Enterprise version sharing | with sharing
[Galaxy Kirin V10] [desktop] login system flash back
Ruby time format conversion strftime MS matching format
Doris / Clickhouse / Hudi, a phased summary in June
TS type gymnastics: illustrating a complex advanced type
Occasional pit compiled by idea
[FAQ] summary of common causes and solutions of Huawei account service error 907135701
Velodyne configuration command
leetcode729. My schedule 1
DNS hijacking
20 minutes to learn what XML is_ XML learning notes_ What is an XML file_ Basic grammatical rules_ How to parse
Sword finger offer 05 (implemented in C language)
【Day2】 convolutional-neural-networks
[Galaxy Kirin V10] [server] iSCSI deployment
Knapsack problem and 0-1 knapsack problem
Latex arranges single column table pictures in double column format articles