search
HomeBackend DevelopmentPython TutorialThe most mysterious function commonly used in Python! In-depth summary of lambda function!

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

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

  • 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)

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)

带有 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

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() 函数的 Lambda

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 函数的优缺点

优点

  • 评估单个表达式的理想选择,应该只评估一次
  • 它可以在定义后立即调用
  • 与相应的普通语法相比,它的语法更紧凑
  • 它可以作为参数传递给高阶函数,例如 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!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment