current position:Home>Python notes (19): anonymous functions

Python notes (19): anonymous functions

2022-01-30 16:50:01 A bowl week

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~

Anonymous functions

stay python in , Except for general use def Outside the defined function , There is another use lambda Defined anonymous functions . This function can be used where any ordinary function can be used , But when defined, it is strictly limited to a single expression . Semantically speaking , It's just the syntax of ordinary functions .

If we need to define a particularly simple function , for example

def add(a, b):
    s = a + b
    return s
 Copy code 

So there's a problem , So elegant Python How can such ugly code appear , Is there any way to simplify it to 1 What about line code ? So elegant Python There must be a way to simplify it ! It used to Anonymous functions 了 .

python Use in **lambda** Keyword to create anonymous functions .

Grammar format

lambda [ Parameters 1 [, Parameters 2,.. Parameters n]]: expression 
 Copy code 

lambda parameter list :return [ expression ] Variable

because lambda What is returned is the function object ( What is built is a function object ), So you need to define a variable to receive

The sample code is as follows :

news_add = lambda a, b: a + b
#  The one above is equal to 
def news_add_old(a, b):
    return a + b

x = news_add_old(5, 10)
y = news_add(5, 10)  #  Call anonymous functions 
print(x, y)  # 15 15
 Copy code 

Use with built-in functions

list1 = [{"a": 10, "b": 20}, {"a": 20, "b": 20}, {"a": 50, "b": 20}, {"a": 6, "b": 20}, {"a": 9, "b": 20}]

#  The one on that list a Maximum 
max_value = max(list1, key=lambda x: x["a"])

#  If you write with ordinary functions, there are a few more lines 
def func(di):
    return di["a"]
max_value = max(list1, key=func)  #  You can't add it here () Otherwise, it means that 
 Copy code 

Take anonymous functions as arguments

def func(a, b, fun):
    s = fun(a, b)
    return s

z = func(5, 10, lambda a, b: a + b)
print(z)  # 15
 Copy code 

lambda The process of defining functions can be omitted , Make the code simpler , And don't worry about naming , But in PEP8 It is not recommended to use in the specification lambda In this way .

copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.

Random recommended