Lambda函数是Python中的一种匿名函数,它可以在需要函数对象的任何地方使用。Lambda函数通常用于函数式编程,特别是在需要一种简洁的方式定义简单函数的情况下。
Lambda函数的一般语法为:
lambda arguments: expression
其中,lambda
是关键字,arguments
是函数的参数(可以是多个,用逗号分隔),expression
是函数的返回值表达式。
比如,你可以使用Lambda函数来定义一个简单的加法函数:
add = lambda x, y: x + y
print(add(3, 5)) # 输出 8
Lambda函数通常与内置的高阶函数(如map()
,filter()
,reduce()
等)结合使用,以提供更简洁的代码。例如:
# 使用map()将列表中的每个元素加1
numbers = [1, 2, 3, 4, 5]
result = map(lambda x: x + 1, numbers)
print(list(result)) # 输出 [2, 3, 4, 5, 6]
# 使用filter()过滤出列表中的偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers)) # 输出 [2, 4, 6, 8, 10]
Lambda函数的主要优点在于它们简洁、内联定义,适合于一次性使用的简单功能。然而,由于其匿名性,Lambda函数通常只用于较短的表达式,对于复杂逻辑,还是建议使用普通的命名函数。
案例1:基本语法
常规函数:
def add(x, y):
return x + y
匿名函数:
lambda_add = lambda x, y: x + y
调用两种类型函数:
print(add(3, 5)) # 输出:8
print(lambda_add(3, 5)) # 输出:8
案例2:在sorted排序函数中使用匿名函数
students = [("Alice", 25), ("Bob", 30), ("Charlie", 22)]
sorted_students = sorted(students, key=lambda student: student[1])
print("Sorted Students by Age:", sorted_students)
# 输出:Sorted Students by Age: [('Charlie', 22), ('Alice', 25), ('Bob', 30)]
案例3:在filter过滤函数中使用匿名函数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print("Even Numbers:", even_numbers)
# 输出:Even Numbers: [2, 4, 6, 8]
案例4:在map函数中使用匿名函数
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print("Squared Numbers:", squared_numbers)
# 输出:Squared Numbers: [1, 4, 9, 16, 25]
案例5:在max函数中使用匿名函数
numbers = [10, 5, 8, 20, 15]
max_number = max(numbers, key=lambda x: -x)
print("Maximum Number:", max_number)
# 输出:Maximum Number: 5
案例6:在sorted排序函数中,多个排序条件
people = [{"name": "Charlie", "age": 25},
{"name": "Bob", "age": 30},
{"name": "Alice", "age": 25}]
sorted_people = sorted(people,
key=lambda person: (person["age"], person["name"]))
print("Sorted People:", sorted_people)
# 输出:Sorted People: [{'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 25}, {'name': 'Bob', 'age': 30}]
案例7:在reduce函数中使用匿名函数
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print("Product of Numbers:", product)
# 输出:Product of Numbers: 120
案例8:在条件表达式中使用匿名函数
numbers = [10, 5, 8, 20, 15]
filtered_and_squared = list(map(lambda x: x**2 if x % 2 == 0 else x, numbers))
print("Filtered and Squared Numbers:", filtered_and_squared)
# 输出:Filtered and Squared Numbers: [100, 5, 64, 400, 15]
如果我有哪里写的不对,欢迎评论区留言进行指正。
如果有收获,记得点赞收藏哦🥰