What is an anonymous function in Python

Anonymous function

lambda x , y : x+y

  1. The purpose of anonymity is to have no name. Assigning a name to an anonymous function is meaningless.

  2. The parameter rules and scope relationship of anonymous functions are the same as those of well-known functions.

  3. The body of an anonymous function should usually be an expression, and the expression must have a return value.

f=lambda x,n:x ** n

print(f(2,3))

Application of lambda anonymous function: max,min,sorted,map,reduce,filter

Seeking the highest salary: max

salaries={'egon':3000,'alex':100000000,'wupeiqi':10000,'yuanhao':2000}
def get(k):return salaries[k]print(max(salaries,key=get)) #'alex'print(max(salaries,key=lambda x:salaries[x]))
info =[{'name':'egon','age':'18','salary':'3000'},{'name':'wxx','age':'28','salary':'1000'},{'name':'lxx','age':'38','salary':'2000'}]max(info, key=lambda dic:int(dic['salary']))max([11,22,33,44,55])

The person seeking the lowest wage: min

salaries={'egon':3000,'alex':100000000,'wupeiqi':10000,'yuanhao':2000}print(min(salaries,key=lambda x:salaries[x]))  # 'yuanhao' 
 info=[{'name':'egon','age':'18','salary':'3000'},{'name':'wxx','age':'28','salary':'1000'},{'name':'lxx','age':'38','salary':'2000'}]min(info,key=lambda dic:int(dic['salary']))

sort sorts the salary dictionary according to salary

salaries={'egon':3000,'alex':100000000,'wupeiqi':10000,'yuanhao':2000}
alaries=sorted(salaries) #Sort by dictionary key by default
print(salaries)
# salaries=sorted(salaries,key=lambda x:salaries[x]) #The default is ascending
alaries=sorted(salaries,key=lambda x:salaries[x],reverse=True) #Descending
print(salaries)
info=[{'name':'egon','age':'18','salary':'3000'},{'name':'wxx','age':'28','salary':'1000'},{'name':'lxx','age':'38','salary':'2000'}]
l=sorted(info,key=lambda dic:int(dic['salary']))

map mapping, loop let each element execute function, save the result of each function execution to a new list

v1 =[11,22,33,44]
result =map(lambda x:x+100,v1) #The first parameter is the function to be executed,The second parameter is an iterable element.print(list(result)) # [111,122,133,144]
names=['alex','wupeiqi','yuanhao','egon']
res=map(lambda x:x+'_NB'if x =='egon'else x +'_SB',names)print(list(res))

reduce, accumulate elements in the parameter sequence

import functools
v1 =['wo','hao','e']
def func(x,y):return x+y
result = functools.reduce(func,v1)print(result)  # wohaoe
result = functools.reduce(lambda x,y:x+y,v1)print(result)  # wohaoe
from functools import reduce
l=['my','name','is','alex','alex','is','sb']
res=reduce(lambda x,y:x+' '+y+' ',l)print(res)
# my name is alex alex is sb

filter, filter by condition

result=filter(lambda x:x   2,[1,2,3,4])print(list(result))
v1 =[11,22,33,'asd',44,'xf']
# General practice
def func(x):iftype(x)== int:return True
 return False
result =filter(func,v1)print(list(result))   # [11,22,33,44]
# Simplified approach
result =filter(lambda x: True iftype(x)== int else False ,v1)print(list(result))
# Minimalist approach
result =filter(lambda x:type(x)== int ,v1)print(list(result))
names=['alex_sb','wxx_sb','yxx_sb','egon']
res=filter(lambda x:True if x.endswith('sb')else False,names)
res=filter(lambda x:x.endswith('sb'),names)print(list(res))    #['alex_sb','wxx_sb','yxx_sb']
ages=[18,19,10,23,99,30]
res=filter(lambda n:n  =30,ages)print(list(res))    #[99,30]
salaries={'egon':3000,'alex':100000000,'wupeiqi':10000,'yuanhao':2000}
res=filter(lambda k:salaries[k]=10000,salaries)print(list(res))      #['alex','wupeiqi']

Content expansion:

Anonymous function call

Step 1: Receive the created anonymous function through a variable.

Step 2: Use variables to call anonymous functions.

For example

The first step: Create an anonymous function, the role is to achieve the sum of two numbers.

lambda num1 , num2 : num1 + num2

Step 2: Use a variable to receive this anonymous function

sum = lambda num1 , num2 : num1 + num2

Step 3: Call this anonymous function

sum(10 , 20)

So far, this article on what is an anonymous function in Python is introduced. For more relevant Python anonymous function knowledge summary content, please search ZaLou.Cn

Recommended Posts

What is an anonymous function in Python
What is the function of adb in python
What is introspection in python
What is object-oriented in python
What is list comprehension in python
Is there function overloading in python
Everything in Python is an object
Is there an algorithm in python language
What is the id function of python
What is a sequence table in Python
What is the function body of python
Is there a helper function in python
Join function in Python
Is python an interpreted language?
What is Python variable scope
What does rc1 mean in python
What does def in python do
What is the use of Python
​What are the numbers in Python?
What does np do in python
What is the scope of python variables
How to run id function in python
What are web development frameworks in python
What system is good for self-study python
What is the prospect of python development
Is a number in python a variable type
Python is mainly used in which directions
How to use the round function in python
Python 3.9 is here!
Functions in python
How to use the zip function in Python
An article to understand the yield in Python
What does the tab key in python mean
How to use the format function in python
What is the difference between python and pycharm
Python enumerate() function
Python function buffer
What is the difference between synchronous and asynchronous Python?
What is the advantage of python over corporate language
What conditions are needed for infinite loop in Python
How to save IE as an attachment in python
What are the ways to open files in python
Why python is popular
Python is short-crawling music
Python is slowly fading
Python custom function basics
What can Python do
12. Network Programming in Python3
print statement in python
Python built-in function -compile()
Python function basic learning
Python data analysis-apply function
Python3 built-in function table.md
Concurrent requests in Python
Install python in Ubuntu
Context management in Python
Arithmetic operators in python
Write gui in python
Python Print print timer function
MongoDB usage in Python
Str string in Python