Python map filter reduce
这是函数式编程的三个核心函数。
1. map - 转换
# 对每个元素执行操作
numbers = [1, 2, 3, 4]
# lambda
result = list(map(lambda x: x * 2, numbers))
# [2, 4, 6, 8]
# 多序列
a = [1, 2, 3]
b = [4, 5, 6]
list(map(lambda x, y: x + y, a, b))
# [5, 7, 9]
2. filter - 过滤
# 保留满足条件的元素
numbers = [1, 2, 3, 4, 5]
result = list(filter(lambda x: x > 2, numbers))
# [3, 4, 5]
3. reduce - 聚合
from functools import reduce
# 累积操作
numbers = [1, 2, 3, 4]
result = reduce(lambda a, b: a + b, numbers)
# 10
初始值
reduce(lambda a, b: a + b, numbers, 100)
# 110
4. 组合使用
# 先过滤,再转换
result = list(map(
lambda x: x * 2,
filter(lambda x: x > 0, numbers)
))
5. functools 其他函数
from functools import partial
# 固定部分参数
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
square(5) # 25
map/filter/reduce 是函数式编程的基础。