Python 什么是lambda函数为什么我们需要它

Python 什么是lambda函数为什么我们需要它

在这篇文章中,我们将学习Python中的lambda函数以及我们为什么需要它,并且看一些lambda函数的实际示例。

Python中的lambda函数是什么

lambda函数,通常被称为 匿名函数 ,与普通的Python函数相同,只是它可以 没有函数名 定义。使用 def 关键字定义普通函数,而使用 lambda 关键字定义匿名函数。然而,它们被限制在一行表达式之内。与常规函数一样,它们可以接受多个参数。

语法

lambda arguments: expression
  • 此函数接受任意数量的输入,但只评估并返回一个表达式。

  • Lambda函数可用于任何需要函数对象的地方。

  • 您必须记住,lambda函数在语法上限制为单个表达式。

  • 除了函数中的其他类型表达式之外,它在编程的特定领域有各种用途。

为什么需要Lambda函数

  • 与使用def关键字编写的普通Python函数相比,lambda函数需要的代码行数更少。然而,这并不完全正确,因为使用def定义的函数可以在一行中定义。但是,通常在多行上定义def函数。

  • 它们通常在需要函数的较短时间(临时)内使用,常常在另一个函数(如filter、map或reduce)内使用。

  • 您可以使用lambda函数定义一个函数,并在定义的末尾立即调用它。这对于def函数是不可能的。

Python Lambda函数的简单示例

示例

# input string 
inputString = 'TUTORIALSpoint'

# converting the given input string to lowercase and reversing it
# with the lambda function
reverse_lower = lambda inputString: inputString.lower()[::-1]

print(reverse_lower(inputString))

输出

执行时,以上程序会生成以下输出结果 –

tniopslairotut

在条件检查中使用Lambda函数

示例

# Formatting number to 2 decimal places using lambda function
formatNum = lambda n: f"{n:e}" if isinstance(n, int) else f"{n:,.2f}"

print("Int formatting:", formatNum(1000))
print("float formatting:", formatNum(5555.4895412))

输出

执行上述程序后,将会产生以下输出 –

Int formatting: 1.000000e+03
float formatting: 5,555.49

Lambda函数和使用def定义的函数之间的区别是什么

示例

# creating a function that returns the square root of 
# the number passed to it
def square(x):
    return x*x


# using lambda function that returns the square root of 
# the number passed 
lambda_square = lambda x: x*x


# printing the square root of the number by passing the
# random number to the above-defined square function with the def keyword
print("Square of the number using the function with 'def' keyword:", square(4))

# printing the square root of the number by passing the
# random number to the above lambda_square function with lambda keyword
print("Square of the number using the function with 'lambda' keyword:", lambda_square(4))

输出

执行时,上述程序将生成以下输出 −

Square of the number using the function with 'def' keyword: 16
Square of the number using the function with 'lambda' keyword: 16

如前面的示例所示, square()lambda_square() 函数的工作方式完全一样,符合预期。让我们仔细看一下这个示例,找出它们之间的区别 –

使用lambda函数 不使用lambda函数
支持返回某个值的单行语句。 允许在函数块中使用任意行数。
适用于执行小操作或数据操作。 在需要多行代码的情况下很有用。
减少代码的可读性。 我们可以通过使用注释和函数解释来提高可读性。

Python lambda函数的实际用途

示例

使用Lambda函数与列表推导式

is_odd_list = [lambda arg=y: arg * 5 for y in range(1, 10)]

# looping on each lambda function and calling the function
# for getting the multiplied value
for i in is_odd_list:
    print(i())

输出

在执行时,以上程序将生成以下输出:

5
10
15
20
25
30
35
40
45

在每次列表推导的迭代中,都会创建一个带有默认参数y的新lambda函数(其中 y 是迭代中的当前项)。稍后,在for循环中,我们使用 i() 来调用同一个函数对象,并使用默认参数获得所需的值。因此, is_odd_list 保存着一组lambda函数对象的列表。

示例

使用lambda函数与if-else条件语句

# using lambda function to find the maximum number among both the numbers
find_maximum = lambda x, y : x if(x > y) else y

print(find_maximum(6, 3))

输出:

执行上述程序后,将生成以下输出:

6

示例

使用带有多个语句的Lambda函数

inputList = [[5,2,8],[2, 9, 12],[10, 4, 2, 7]]

# sorting the given each sublist using lambda function
sorted_list = lambda k: (sorted(e) for e in k)

# getting the second-largest element 
second_largest = lambda k, p : [x[len(x)-2] for x in p(k)]
output = second_largest(inputList, sorted_list)

# printing the second largest element
print(output)

输出

执行上述程序后,将生成以下输出 –

[5, 9, 7]

Python lambda函数与filter()

示例

inputList = [3, 5, 10, 7, 24, 6, 1, 12, 8, 4]

# getting the even numbers from the input list 
# using lambda and filter functions
evenList = list(filter(lambda n: (n % 2 == 0), inputList))
# priting the even numbers from the input list
print("Even numbers from the input list:", evenList)

输出

在执行时,上述程序将生成以下输出 −

Even numbers from the input list: [10, 24, 6, 12, 8, 4]

Python lambda函数与map()

Python的map() 函数接受一个函数和一个列表作为参数。该函数使用lambda函数和列表调用,它返回一个新列表,其中包含每个项目为lambda修改后返回的项。

示例

使用lambda和map()函数将所有列表元素转换为小写

# input list
inputList = ['HELLO', 'TUTORIALSpoint', 'PyTHoN', 'codeS']

# converting all the input list elements to lowercase using lower()
# with the lambda() and map() functions and returning the result list
lowercaseList = list(map(lambda animal: animal.lower(), inputList))

# printing the resultant list
print("Converting all the input list elements to lowercase:\n", lowercaseList)

输出

在执行后,上述程序将生成以下输出 −

Converting all the input list elements to lowercase:
 ['hello', 'tutorialspoint', 'python', 'codes']

结论

在本教程中,我们深入学习了Python中的lambda函数,并给出了许多示例。我们还学习了lambda函数和def函数之间的区别。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程