The most mysterious function commonly used in Python! In-depth summary of lambda function!

WBOY
Release: 2023-04-12 23:13:09
forward
1409 people have browsed it

The most mysterious function commonly used in Python! In-depth summary of lambda function!

What is the Lambda function in Python

The lambda function is an anonymous function (i.e., no name is defined) that can accept any number of parameters, but has the same Functions are different in that they only evaluate and return an expression.

The lambda function in Python is expressed using the following syntax:

lambda parameters: expression

The lambda function consists of three elements:

  • Key Word lambda: similar to def in ordinary functions
  • Parameters: Supports passing positional and keyword parameters, the same as ordinary functions
  • Text: Processing expressions with fixed parameters

It should be noted that, unlike ordinary functions, there is no need to use parentheses to enclose the parameters of the lambda function. If the lambda function has two or more parameters, we list them with commas

We use lambda The function only evaluates a short expression (ideally, a single line) and only evaluates it once, which means we won't reuse the function again in the future. Generally speaking, we will pass the lambda function as a parameter to a higher-order function (a function that accepts other functions as parameters), such as Python built-in functions, such as filter(), map() or reduce(), etc.

Python How the Lambda function works in

Let us look at a simple lambda function example:

lambda x: x + 1
Copy after login

Output:

<function __main__.<lambda>(x)>
Copy after login

The above lambda function accepts a parameter and increments it by 1 , and then returns the result

It is a simpler version of the following ordinary function with the def and return keywords:

def increment_by_one(x):
 return x + 1
Copy after login

So far our lambda function lambda x: x 1 only creates one function Object, returns nothing because we did not provide any value (argument) for its parameter x. Let's first assign a variable, pass it to the lambda function, and see what we get this time:

a = 2
print(lambda x: a + 1)
Copy after login

Output:

<function <lambda> at 0x00000250CB0A5820>
Copy after login

Our lambda function doesn't return as we expected 3. Instead, the function object itself and its memory location are returned. It can be seen that this is not the correct way to call the lambda function. To pass parameters to a lambda function, execute it and return the result, we should use the following syntax:

(lambda x: x + 1)(2)
Copy after login

Output:

3
Copy after login
Copy after login

Although the parameters of our lambda function are not enclosed in parentheses, When we call it, we add brackets around the entire construction of the lambda function and the arguments we pass to it

Another thing to note in the above code is that with lambda functions, we can create Execute the function immediately after the function and receive the result. This is called Immediate Invocation of Function Execution (or IIFE)

We can create a lambda function with multiple parameters, in which case we separate the parameters in the function definition with commas. When we execute such a lambda function, we list the corresponding parameters in the same order and separate them with commas:

(lambda x, y, z: x + y + z)(3, 8, 1)
Copy after login

Output:

12
Copy after login

You can also use lambda functions to perform conditional operations . Here is a lambda simulation of a simple if-else function:

print((lambda x: x if(x > 10) else 10)(5))
print((lambda x: x if(x > 10) else 10)(12))
Copy after login

Output:

10
12
Copy after login

If there are multiple conditions (if-elif-...-else), we must nest them :

(lambda x: x * 10 if x > 10 else (x * 5 if x < 5 else x))(11)
Copy after login

Output:

110
Copy after login
Copy after login

But the above writing method makes the code difficult to read

In this case, with if-elif-...- Ordinary functions with else condition sets would be a better choice than lambda functions. In fact, we can write the lambda function in the above example by:

def check_conditions(x):
 if x > 10:
 return x * 10
 elif x < 5:
 return x * 5
 else:
 return x
check_conditions(11)
Copy after login

Output:

110
Copy after login
Copy after login

Although the above function adds more lines than the corresponding lambda function, it is more Easy to read

We can assign the lambda function to a variable and then call that variable as a normal function:

increment = lambda x: x + 1
increment(2)
Copy after login

Output:

3
Copy after login
Copy after login

But according to PEP 8 of Python code Style rules, this is bad practice

  • The use of assignment statements eliminates the only benefit that lambda expressions can provide over explicit def statements (i.e., it can be embedded in larger expression)

So if we really need to store a function for further use, we are better off defining an equivalent normal function instead of assigning the lambda function to a variable

Application of Lambda function in Python

Lambda with filter() function

The filter() function in Python requires two parameters:

  • The function that defines the filter conditions
  • The iterable object on which the function runs

Running the function, we get a filter object:

lst = [33, 3, 22, 2, 11, 1]
filter(lambda x: x > 10, lst)
Copy after login

Output:

<filter at 0x250cb090520>
Copy after login

In order to get a new iterator from the filter object, and all items in the original iterator meet the predefined conditions, we need to pass the filter object to the corresponding function of the Python standard library: list (), tuple(), set (), frozenset() or sorted() (returns a sorted list)

Let's filter a list of numbers to select only numbers greater than 10 and return a list sorted in ascending order :

lst = [33, 3, 22, 2, 11, 1]
sorted(filter(lambda x: x > 10, lst))
Copy after login

Output:

[11, 22, 33]
Copy after login

We don’t have to create a new iterable object of the same type as the original object, plus we can store the result of this operation in a variable:

lst = [33, 3, 22, 2, 11, 1]
tpl = tuple(filter(lambda x: x > 10, lst))
tpl
Copy after login

Output:

(33, 22, 11)
Copy after login

带有 map() 函数的 Lambda

我们使用 Python 中的 map() 函数对可迭代的每个项目执行特定操作。它的语法与 filter() 相同:一个要执行的函数和一个该函数适用的可迭代对象。

map() 函数返回一个 map 对象,我们可以通过将该对象传递给相应的 Python 函数来从中获取一个新的迭代:list()、tuple()、set()、frozenset() 或 sorted()

与 filter() 函数一样,我们可以从 map 对象中提取与原始类型不同类型的可迭代对象,并将其分配给变量。

下面是使用 map() 函数将列表中的每个项目乘以 10 并将映射值作为分配给变量 tpl 的元组输出的示例:

lst = [1, 2, 3, 4, 5]
print(map(lambda x: x * 10, lst))
tpl = tuple(map(lambda x: x * 10, lst))
tpl
Copy after login

Output:

<map object at 0x00000250CB0D5F40>
(10, 20, 30, 40, 50)
Copy after login

map() 和 filter() 函数之间的一个重要区别是第一个函数总是返回与原始函数相同长度的迭代。因此由于 pandas Series 对象也是可迭代的,我们可以在 DataFrame 列上应用 map() 函数来创建一个新列:

import pandas as pd
df = pd.DataFrame({'col1': [1, 2, 3, 4, 5], 'col2': [0, 0, 0, 0, 0]})
print(df)
df['col3'] = df['col1'].map(lambda x: x * 10)
df
Copy after login

Output:

col1col2
0 1 0
1 2 0
2 3 0
3 4 0
4 5 0
col1col2col3
0 1 010
1 2 020
2 3 030
3 4 040
4 5 050
Copy after login

当然要在上述情况下获得相同的结果,也可以使用 apply() 函数:

df['col3'] = df['col1'].apply(lambda x: x * 10)
df
Copy after login

Output:

col1col2col3
0 1 010
1 2 020
2 3 030
3 4 040
4 5 050
Copy after login

我们还可以根据某些条件为另一列创建一个新的 DataFrame 列,对于下面的代码,我们可以互换使用 map() 或 apply() 函数:

df['col4'] = df['col3'].map(lambda x: 30 if x < 30 else x)
df
Copy after login

Output:

col1col2col3col4
0 1 01030
1 2 02030
2 3 03030
3 4 04040
4 5 05050
Copy after login

带有 reduce() 函数的 Lambda

reduce() 函数与 functools Python 模块相关,它的工作方式如下:

  • 对可迭代对象的前两项进行操作并保存结果
  • 对保存的结果和可迭代的下一项进行操作
  • 以这种方式在值对上进行,直到所有项目使用可迭代的

该函数与前两个函数具有相同的两个参数:一个函数和一个可迭代对象。但是与前面的函数不同的是,这个函数不需要传递给任何其他函数,直接返回结果标量值:

from functools import reduce
lst = [1, 2, 3, 4, 5]
reduce(lambda x, y: x + y, lst)
Copy after login

Output:

15
Copy after login

上面的代码展示了我们使用 reduce() 函数计算列表总和时的作用

需要注意的是,reduce() 函数总是需要一个带有两个参数的 lambda 函数,而且我们必须首先从 functools Python 模块中导入它

Python 中 Lambda 函数的优缺点

优点

  • 评估单个表达式的理想选择,应该只评估一次
  • 它可以在定义后立即调用
  • 与相应的普通语法相比,它的语法更紧凑
  • 它可以作为参数传递给高阶函数,例如 filter()、map() 和 reduce()

缺点

  • 它不能执行多个表达式
  • 它很容易变得麻烦,可读性差,例如当它包括一个 if-elif-...-else 循环
  • 它不能包含任何变量赋值(例如,lambda x: x=0 将抛出一个语法错误)
  • 我们不能为 lambda 函数提供文档字符串

总结

总而言之,我们已经详细讨论了在 Python 中定义和使用 lambda 函数的许多方面:

  • lambda 函数与普通 Python 函数有何不同
  • Python 中 lambda 函数的语法和剖析
  • 何时使用 lambda 函数
  • lambda 函数的工作原理
  • 如何调用 lambda 函数
  • 调用函数执行(IIFE)的定义
  • 如何使用 lambda 函数执行条件操作,如何嵌套多个条件,以及为什么我们应该避免它
  • 为什么我们应该避免将 lambda 函数分配给变量
  • 如何将 lambda 函数与 filter() 函数一起使用
  • 如何将 lambda 函数与 map() 函数一起使用
  • 我们如何在 pandas DataFrame 中使用
  • 带有传递给它的 lambda 函数的 map() 函数 - 以及在这种情况下使用的替代功能
  • 如何将 lambda 函数与 reduce() 函数一起使用
  • 普通 Python 上使用 lambda 函数的优缺点

希望今天的讨论可以使 Python 中看似令人生畏的 lambda 函数概念更清晰、更易于应用,更希望小伙伴们能够喜欢,喜欢就点个赞吧!

The above is the detailed content of The most mysterious function commonly used in Python! In-depth summary of lambda function!. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!