Python Anonymous Function Details

  • 2021-12-12 05:01:50
  • OfStack

Directory 1, anonymous function 2, built-in function using

1. Anonymous functions

In python In, except for 1 def In addition to the functions defined, there is also an anonymous function defined by lambda. This function can be used wherever ordinary functions can be used, but it is strictly limited to a single 1 expression when defined. Semantically speaking, it is just the grammatical sugar of ordinary functions.

If we need to define a particularly simple function, such as


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

That's a problem, so elegant Python How can this ugly code appear, and is there any way to simplify it to 1 line of code? So elegant Python There must be a way to simplify it! This requires anonymous functions.

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

Syntax format:

lambda [参数1 [,参数2,..参数n]]:表达式

lambda Parameter list: return Expression variable

Due to lambda Returns a function object (1 function object is built), so you need to define a variable to receive it

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 function 
print(x, y)  # 15 15

2. Use of built-in functions

Use in conjunction 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}]

#  In that list a Maximum 
max_value = max(list1, key=lambda x: x["a"])
print(max_value)

#  If you write in ordinary functions, you will have 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 calling 
print(max_value)

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

lambda You can save the process of defining functions, make the code simpler, and don't consider naming problems, but in PEP8 It is not recommended in the specification lambda In this way.


Related articles: