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:
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.
Let us look at a simple lambda function example:
lambda x: x + 1
Output:
<function __main__.<lambda>(x)>
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
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)
Output:
<function <lambda> at 0x00000250CB0A5820>
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)
Output:
3
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)
Output:
12
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))
Output:
10 12
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)
Output:
110
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)
Output:
110
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)
Output:
3
But according to PEP 8 of Python code Style rules, this is bad practice
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
The filter() function in Python requires two parameters:
Running the function, we get a filter object:
lst = [33, 3, 22, 2, 11, 1] filter(lambda x: x > 10, lst)
Output:
<filter at 0x250cb090520>
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))
Output:
[11, 22, 33]
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
Output:
(33, 22, 11)
我们使用 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
Output:
<map object at 0x00000250CB0D5F40> (10, 20, 30, 40, 50)
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
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
当然要在上述情况下获得相同的结果,也可以使用 apply() 函数:
df['col3'] = df['col1'].apply(lambda x: x * 10) df
Output:
col1col2col3 0 1 010 1 2 020 2 3 030 3 4 040 4 5 050
我们还可以根据某些条件为另一列创建一个新的 DataFrame 列,对于下面的代码,我们可以互换使用 map() 或 apply() 函数:
df['col4'] = df['col3'].map(lambda x: 30 if x < 30 else x) df
Output:
col1col2col3col4 0 1 01030 1 2 02030 2 3 03030 3 4 04040 4 5 05050
reduce() 函数与 functools Python 模块相关,它的工作方式如下:
该函数与前两个函数具有相同的两个参数:一个函数和一个可迭代对象。但是与前面的函数不同的是,这个函数不需要传递给任何其他函数,直接返回结果标量值:
from functools import reduce lst = [1, 2, 3, 4, 5] reduce(lambda x, y: x + y, lst)
Output:
15
上面的代码展示了我们使用 reduce() 函数计算列表总和时的作用
需要注意的是,reduce() 函数总是需要一个带有两个参数的 lambda 函数,而且我们必须首先从 functools Python 模块中导入它
优点
总而言之,我们已经详细讨论了在 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!