← 返回首页
🐍

Lambda表达式

📂 python ⏱ 3 min 415 words

什么是Lambda表达式

Lambda表达式是Python中创建匿名函数的一种简洁方式。它允许你用一行代码定义一个简单的函数,而不需要使用def关键字。

# 普通函数
def add(x, y):
    return x + y

# Lambda表达式
add_lambda = lambda x, y: x + y

print(add(3, 5))        # 输出: 8
print(add_lambda(3, 5))  # 输出: 8

Lambda函数的语法非常简洁:lambda 参数: 表达式。它只能包含一个表达式,不能包含复杂的语句。

Lambda表达式的常见用法

Lambda最常见的用途是作为高阶函数的参数。高阶函数是接受函数作为参数的函数,如map()filter()sorted()

# 作为回调函数
def apply_operation(x, y, operation):
    return operation(x, y)

result = apply_operation(5, 3, lambda a, b: a + b)
print(result)  # 输出: 8

map()函数

map()函数接受一个函数和一个可迭代对象,将函数应用到每个元素上。

numbers = [1, 2, 3, 4, 5]

# 将每个数字平方
squared = list(map(lambda x: x**2, numbers))
print(squared)  # 输出: [1, 4, 9, 16, 25]

# 将字符串转为大写
words = ['hello', 'world', 'python']
upper_words = list(map(lambda w: w.upper(), words))
print(upper_words)  # 输出: ['HELLO', 'WORLD', 'PYTHON']

# 多个可迭代对象
a = [1, 2, 3]
b = [10, 20, 30]
sums = list(map(lambda x, y: x + y, a, b))
print(sums)  # 输出: [11, 22, 33]

filter()函数

filter()函数用于过滤可迭代对象,返回满足条件的元素。

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 过滤偶数
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # 输出: [2, 4, 6, 8, 10]

# 过滤非空字符串
words = ['hello', '', 'world', '', 'python']
non_empty = list(filter(lambda w: len(w) > 0, words))
print(non_empty)  # 输出: ['hello', 'world', 'python']

sorted()函数与key参数

sorted()函数的key参数接受一个函数,用于指定排序依据。

students = [
    {'name': 'Alice', 'age': 25, 'score': 90},
    {'name': 'Bob', 'age': 22, 'score': 85},
    {'name': 'Charlie', 'age': 23, 'score': 92}
]

# 按年龄排序
by_age = sorted(students, key=lambda s: s['age'])
print([s['name'] for s in by_age])  # 输出: ['Bob', 'Charlie', 'Alice']

# 按分数降序排序
by_score_desc = sorted(students, key=lambda s: s['score'], reverse=True)
print([s['name'] for s in by_score_desc])  # 输出: ['Charlie', 'Alice', 'Bob']

# 复杂排序:先按姓氏,再按名字
names = ['Charlie Brown', 'Alice Smith', 'Bob Jones', 'Alice Adams']
sorted_names = sorted(names, key=lambda n: (n.split()[1], n.split()[0]))
print(sorted_names)  # 输出: ['Alice Adams', 'Alice Smith', 'Bob Jones', 'Charlie Brown']

Lambda与列表推导式

在很多情况下,Lambda可以和列表推导式互相替代,但各有优势。

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 使用map和lambda
squared_map = list(map(lambda x: x**2, numbers))

# 使用列表推导式
squared_list = [x**2 for x in numbers]

# 两者结果相同
print(squared_map == squared_list)  # 输出: True

# 使用filter和lambda
evens_map = list(filter(lambda x: x % 2 == 0, numbers))

# 使用列表推导式
evens_list = [x for x in numbers if x % 2 == 0]

print(evens_map == evens_list)  # 输出: True

实际应用案例

# 1. 排序字典列表
employees = [
    {'name': 'John', 'salary': 50000},
    {'name': 'Jane', 'salary': 60000},
    {'name': 'Bob', 'salary': 45000}
]

# 按薪资排序
by_salary = sorted(employees, key=lambda e: e['salary'])

# 2. 选择特定键
names = list(map(lambda e: e['name'], employees))
print(names)  # 输出: ['John', 'Jane', 'Bob']

# 3. 数据转换
temperatures_c = [0, 20, 37, 100]
temperatures_f = list(map(lambda c: c * 9/5 + 32, temperatures_c))
print(temperatures_f)  # 输出: [32.0, 68.0, 98.6, 212.0]

# 4. 条件过滤
scores = [85, 92, 78, 95, 88]
passed = list(filter(lambda s: s >= 80, scores))
print(passed)  # 输出: [85, 92, 95, 88]

最佳实践

掌握Lambda表达式能让你的Python代码更加简洁和优雅,尤其在处理函数式编程风格的代码时非常有用。