首页 > 文章列表 > Python中的lambda函数是什么,为什么我们需要它?

Python中的lambda函数是什么,为什么我们需要它?

Python Lambda函数 需要
112 2023-08-30

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

Python 中的 lambda 函数是什么?

Lambda 函数通常称为“匿名函数”, 与普通 Python 函数相同,只不过它可以不带名称进行定义。 >def关键字用于定义普通函数,而lambda关键字用于定义匿名函数。然而,它们仅限于单行表达。它们与常规函数一样,可以接受多个参数。

语法

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

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

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

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

为什么我们需要 Lambda 函数?

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

  • 它们通常在需要较短时间(临时)的函数时使用,通常在另一个函数(例如过滤器、映射或归约)中使用。

  • 您可以定义一个函数并在定义结束时使用 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]

带有filter()的Python lambda函数

示例

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]

带有map()的Python lambda函数

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 函数之间的区别。