摘要:Lambda函数是Python中的一种特殊函数,它没有名字(所以叫匿名函数),用于创建简单的、一次性的函数。它就像一个"快捷方式",让你快速定义简单的函数而不需要使用def关键字。
Lambda函数是Python中的一种特殊函数,它没有名字(所以叫匿名函数),用于创建简单的、一次性的函数。它就像一个"快捷方式",让你快速定义简单的函数而不需要使用def关键字。
# 普通函数定义def add(x, y): return x + y# Lambda函数定义add_lambda = lambda x, y: x + y# 使用对比print(add(3, 5)) # 输出: 8print(add_lambda(3, 5)) # 输出: 8# 正确的Lambda函数multiply = lambda a, b: a * b# 错误的Lambda函数(不能包含多条语句)# wrong_lambda = lambda x: print(x); return x * 2 # 语法错误!# 配合map函数numbers = [1, 2, 3, 4, 5]squared = list(map(lambda x: x ** 2, numbers))print(squared) # 输出: [1, 4, 9, 16, 25]# 配合filter函数even_numbers = list(filter(lambda x: x % 2 == 0, numbers))print(even_numbers) # 输出: [2, 4]# 配合sorted函数students = [("Alice", 90), ("Bob", 85), ("Charlie", 92)]# 按成绩排序sorted_by_grade = sorted(students, key=lambda student: student[1])print(sorted_by_grade) # 输出: [('Bob', 85), ('Alice', 90), ('Charlie', 92)]# 定义一个接受函数作为参数的函数def apply_operation(x, y, operation): return operation(x, y)# 使用Lambda函数作为参数result1 = apply_operation(10, 5, lambda a, b: a + b)result2 = apply_operation(10, 5, lambda a, b: a * b)result3 = apply_operation(10, 5, lambda a, b: a if a > b else b)print(f"加法结果: {result1}") # 输出: 15print(f"乘法结果: {result2}") # 输出: 50print(f"较大值: {result3}") # 输出: 10# 两个参数add = lambda x, y: x + yprint(add(3, 4)) # 输出: 7# 三个参数calculate = lambda a, b, c: (a + b) * cprint(calculate(2, 3, 4)) # 输出: 20# 无参数greet = lambda: "Hello, World!"print(greet) # 输出: Hello, World!# 学生数据students = [ {"name": "小明", "math": 85, "english": 90}, {"name": "小红", "math": 92, "english": 88}, {"name": "小刚", "math": 78, "english": 85}]# 按数学成绩排序sorted_by_math = sorted(students, key=lambda s: s["math"], reverse=True)print("按数学成绩排序:", sorted_by_math)# 计算每个学生的平均分students_with_avg = list(map(lambda s: { "name": s["name"], "average": (s["math"] + s["english"]) / 2}, students))print("带平均分的学生数据:", students_with_avg)names = ["alice", "BOB", "charlie", "Diana"]# 将所有名字转换为首字母大写proper_names = list(map(lambda name: name.title, names))print(proper_names) # 输出: ['Alice', 'Bob', 'Charlie', 'Diana']# 过滤出长度大于3的名字long_names = list(filter(lambda name: len(name) > 3, names))print(long_names) # 输出: ['alice', 'BOB', 'charlie', 'Diana']示例3:数学运算# 创建简单的数学函数集合math_operations = { "square": lambda x: x ** 2, "cube": lambda x: x ** 3, "reciprocal": lambda x: 1 / x if x != 0 else "无穷大", "abs": lambda x: x if x >= 0 else -x}# 使用print(math_operations["square"](5)) # 输出: 25print(math_operations["cube"](3)) # 输出: 27print(math_operations["reciprocal"](4)) # 输出: 0.25print(math_operations["abs"](-7)) # 输出: 7# 复杂的Lambda函数难以理解confusing = lambda x: "正数" if x > 0 else "零" if x == 0 else "负数"# 普通函数更清晰def classify_number(x): if x > 0: return "正数" elif x == 0: return "零" else: return "负数"# 适合使用Lambda的场景numbers = [1, 2, 3, 4, 5]doubled = list(map(lambda x: x * 2, numbers)) # 简单明了# 不适合使用Lambda的场景# complex_logic = lambda x: [i for i in range(x) if i % 2 == 0] # 太复杂,不易读记住:如果Lambda函数变得复杂,就改用普通函数!Lambda最适合简单的、一行就能搞定的操作。
来源:琢磨先生起飞吧
