Introduction to Lambda expressions A lambda expression is an anonymous function that allows you to pass a function as an argument to another function. It provides a concise syntax that simplifies code readability. Lambda expressions are also widely used in functional programming and anonymous function definitions.
# 计算两个数字的和 sum = lambda a, b: a + b print(sum(10, 20)) # 计算一个数字的平方 square = lambda x: x ** 2 print(square(5)) # 判断一个数字是否为偶数 is_even = lambda n: n % 2 == 0 print(is_even(7)) # 根据条件执行计算 calculate = lambda x, y, op: x + y if op == "+" else x - y print(calculate(10, 5, "+")) print(calculate(10, 5, "-")) # 在函数中使用Lambda表达式 def apply_function(func, arg): return func(arg) print(apply_function(lambda x: x ** 2, 10)) # 使用Lambda表达式作为过滤器 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers)
combination, filtering, and mapping.
The above is the detailed content of Master Python Lambda expressions and become a programming expert. For more information, please follow other related articles on the PHP Chinese website!