### Python函数式编程lambda、map与filter实用指南

#### 1. lambda表达式

lambda用于创建匿名函数,适用于简单操作,无需定义完整函数。

语法:`lambda 参数: 表达式`

示例:

```python

# 计算平方

square = lambda x: x 2

print(square(5)) # 输出:25

# 多参数lambda

add = lambda a, b: a + b

print(add(3, 7)) # 输出:10

```

适用场景:

- 简单单行函数逻辑

- 作为参数传递给高阶函数(如map、filter)

---

#### 2. map函数

map对可迭代对象中的每个元素应用指定函数,返回迭代器。

语法:`map(函数, 可迭代对象)`

示例:

```python

# 将列表元素转换为字符串

numbers = [1, 2, 3, 4]

str_numbers = list(map(str, numbers))

print(str_numbers) # 输出:['1', '2', '3', '4']

# 结合lambda使用

squared = list(map(lambda x: x2, [1, 2, 3, 4]))

print(squared) # 输出:[1, 4, 9, 16]

# 多列表操作

result = list(map(lambda x, y: x + y, [1, 2], [3, 4]))

print(result) # 输出:[4, 6]

```

适用场景:

- 批量数据转换

- 并行处理多个可迭代对象

---

#### 3. filter函数

filter根据指定函数的条件过滤可迭代对象,返回满足条件的元素迭代器。

语法:`filter(函数, 可迭代对象)`

示例:

```python

# 过滤偶数

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

evens = list(filter(lambda x: x % 2 == 0, numbers))

print(evens) # 输出:[2, 4, 6]

# 过滤非空字符串

words = ['hello', '', 'world', '', '!']

non_empty = list(filter(None, words))

print(non_empty) # 输出:['hello', 'world', '!']

# 复杂条件过滤

ages = [18, 25, 12, 30, 15]

adults = list(filter(lambda x: x >= 18, ages))

print(adults) # 输出:[18, 25, 30]

```

适用场景:

- 数据筛选

- 条件过滤

---

#### 4. 组合使用示例

```python

# 处理数字列表:过滤奇数后求平方

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

result = list(map(lambda x: x2, filter(lambda x: x % 2 == 0, numbers)))

print(result) # 输出:[4, 16, 36, 64]

# 处理字符串列表:过滤空值后转换为大写

words = ['python', '', 'functional', ' ', 'programming']

processed = list(map(str.upper, filter(str.strip, words)))

print(processed) # 输出:['PYTHON', 'FUNCTIONAL', 'PROGRAMMING']

```

---

#### 5. 注意事项

1. 返回值类型:map和filter返回迭代器,需用list()转换为列表

2. 性能考虑:对于复杂操作,考虑使用列表推导式

3. 可读性:避免过度嵌套,保持代码清晰

通过合理运用lambda、map和filter,可以编写出更简洁、高效的Python代码,特别适合数据处理和转换场景。

Logo

码道开发者社区,聚焦华为云码道 CodeArts 代码智能体,沉淀 Agent、Skill、鸿蒙开发实战内容,供开发者查阅资料、交流技术、分享工程实践

更多推荐