### 1. 列表排序与自定义键

在数据处理时,经常需要对列表中的字典或对象按特定字段排序。`lambda` 可以快速定义排序规则,无需编写独立的函数。

示例:

```python

students = [{name: Alice, age: 24}, {name: Bob, age: 20}, {name: Charlie, age: 22}]

students_sorted = sorted(students, key=lambda x: x[age])

print(students_sorted) # 按年龄升序排列

```

---

### 2. 函数式编程中的 `map` 与 `filter`

`lambda` 结合 `map` 或 `filter` 能简洁地对集合进行转换或筛选,避免显式循环。

示例:

```python

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

squared = list(map(lambda x: x2, numbers)) # 平方处理

evens = list(filter(lambda x: x % 2 == 0, numbers)) # 筛选偶数

```

---

### 3. 作为高阶函数的参数

在需要短时回调函数的场景(如 `sort`、`max`/`min` 的 `key` 参数)中,`lambda` 可直接内联定义,简化代码。

示例:

```python

words = [apple, bee, cat, elephant]

longest_word = max(words, key=lambda w: len(w)) # 找到最长单词

```

---

### 4. 动态生成简单函数

对于需要快速生成微小功能的场景(如事件处理或条件判断),`lambda` 提供轻量级的函数定义方式。

示例:

```python

is_positive = lambda x: x > 0

print(is_positive(5)) # 输出 True

```

---

### 5. Pandas 数据操作

在 `pandas` 中,`lambda` 常用于 `apply()` 方法,对 `DataFrame` 或 `Series` 进行逐元素操作。

示例:

```python

import pandas as pd

df = pd.DataFrame({score: [85, 92, 78]})

df[grade] = df[score].apply(lambda s: A if s >= 90 else B)

```

---

### 总结

`lambda` 通过匿名函数特性,在需要简洁单行功能的场景中显著提升代码可读性与编写效率。合理使用可减少冗余代码,但需注意其适用于简单逻辑,复杂功能仍应使用常规函数。

更多推荐