Detailed explanation and use of Python's Lambda function

        When you need to complete a small job, using this function in the local environment can make the work so handy, it is the Lambda function.

        Lambda functions are anonymous functions in Python. Some people refer to them simply as lambdas, and their syntax is as follows:

lambda arguments: expression

        The lambda keyword can be used to create a lambda function, followed by a list of parameters and individual expressions separated by colons. For example, lambda x: 2 * x multiplies any input number by 2, and lambda x, y: x+y calculates the sum of two numbers. The syntax is pretty straightforward, right?

        Assuming you know what a lambda function is, this article aims to provide some general guidelines on how to use lambda functions correctly.

1. Do not return any value

        Looking at the syntax, you might notice that we didn't return anything in the lambda function. This is all because a lambda function can only contain one expression. However, using the return keyword would result in an ungrammatical statement, as follows:

>>> integers = [(3, -3), (2, 3), (5, 1), (-4, 4)]
>>> sorted(integers, key=lambda x: x[-1])
[(3, -3), (5, 1), (2, 3), (-4, 4)]
>>> sorted(integers, key=lambda x: return x[-1])
... 
  File "", line 1
    sorted(integers, key=lambda x: return x[-1])
                                   ^
SyntaxError: invalid syntax

        The error may be caused by inability to distinguish between expressions and statements. Statements like return, try, with, and if perform special actions. However, expressions refer to those expressions that can be evaluated to a value, such as numbers or other Python objects.

        By using lambda functions, a single expression is evaluated as a value and participates in subsequent calculations, such as sorting by the sorted function.

2. Don't forget about better options

        The most common usage scenario of lambda function is to use it as the actual parameter of key in some built-in utility functions, such as sorted() and max() shown above. Depending on the situation, we can use other alternatives. Consider the following example:

>>> integers = [-4, 3, 7, -5, -2, 6]
>>> sorted(integers, key=lambda x: abs(x))
[-2, 3, -4, -5, 6, 7]
>>> sorted(integers, key=abs)
[-2, 3, -4, -5, 6, 7]
>>> scores = [(93, 100), (92, 99), (95, 94)]
>>> max(scores, key=lambda x: x[0] + x[1])
(93, 100)
>>> max(scores, key=sum)
(93, 100)

        In the field of data science, many people use the pandas library to process data. As shown below, we can use lambda function to create new data from existing data through map() function. Instead of using lambda functions, we can also use arithmetic functions directly, since pandas supports them:

>>> import pandas as pd
>>> data = pd.Series([1, 2, 3, 4])
>>> data.map(lambda x: x + 5)
0    6
1    7
2    8
3    9
dtype: int64
>>> data + 5
0    6
1    7
2    8
3    9
dtype: int64

3. Don't assign it to a variable

        I've seen some people mistake lambda functions for just another way of declaring simple functions, and you've probably seen people do things like this:

>>> import pandas as pd
>>> data = pd.Series([1, 2, 3, 4])
>>> data.map(lambda x: x + 5)
0    6
1    7
2    8
3    9
dtype: int64
>>> data + 5
0    6
1    7
2    8
3    9
dtype: int64

        The only use of naming lambda functions is probably for pedagogical purposes, to show that lambda functions are indeed functions like any other—can be called and do something. Besides that, we should not assign lambda functions to variables.

        The problem with naming lambda functions is that it makes debugging less intuitive. Unlike other functions created with the regular def keyword, lambda functions have no name, which is why they are sometimes called anonymous functions. Consider the following simple example and spot the subtle difference:

>>> inversive0 = lambda x: 1 / x
>>> inversive0(2)
0.5
>>> inversive0(0)
Traceback (most recent call last):
  File "", line 1, in <module>
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> def inversive1(x):
...     return 1 / x
... 
>>> inversive1(2)
0.5
>>> inversive1(0)
Traceback (most recent call last):
  File "", line 1, in <module>
  File "", line 2, in inversive1
ZeroDivisionError: division by zero

        When your code has a problem with the lambda function (ie inversive0), the Traceback error message will only prompt you that there is a problem with the lambda function.

        In contrast, with a normally defined function, Traceback will clearly prompt you for the problematic function (ie inversive1).

        On a related note, if you want to use a lambda function multiple times, the best practice is to use a regular function defined via def that allows docstrings.

4. Don’t Forget List Comprehensions

        Some people like to use lambda functions with higher-order functions, such as map or filter. Consider the following usage example:

>>> # 创建一个数字列表
>>> numbers = [2, 1, 3, -3]
>>> # 使用带有 lambda 函数的 map 函数
>>> list(map(lambda x: x * x, numbers))
[4, 1, 9, 9]
>>> # 使用带有 lambda 函数的 filter 函数
>>> list(filter(lambda x: x % 2, numbers))
[1, 3, -3]

        Instead of lambda functions, we can use more readable list comprehensions. As shown below, we use a list comprehension to create the same list object. As you can see, it was more troublesome to use map or filter functions with lambda functions than with list comprehensions. Therefore, list comprehensions should be considered when creating lists involving higher-order functions.

>>> # Use list comprehensions
>>> [x * x for x in numbers]
[4, 1, 9, 9]
>>> [x for x in numbers if x % 2]
[1, 3, -3]

in conclusion

        In this article, we review four common mistakes you can make with lambda functions. By avoiding these mistakes, you should be able to use lambda functions correctly in your code.

        A rule of thumb with lambda functions is to keep it simple and use it locally only once.

Guess you like

Origin blog.csdn.net/huanxiajioabu/article/details/131590496