高阶函数是 Python 中函数式编程的核心概念,它们可以接受函数作为参数,或返回函数作为结果。以下是常见用法与示例:

🧠 1. map() 函数

将函数应用于可迭代对象的每个元素

def square(x):
    return x**2

numbers = [1, 2, 3, 4]
squares = list(map(square, numbers))
# 输出: [1, 4, 9, 16]
Python_Functions

🔢 2. filter() 函数

过滤满足条件的元素

def is_even(x):
    return x % 2 == 0

even_numbers = list(filter(is_even, range(10)))
# 输出: [0, 2, 4, 6, 8]
Higher_Order_Functions

🧮 3. reduce() 函数

对序列进行累积操作

from functools import reduce

def add(x, y):
    return x + y

result = reduce(add, [1, 2, 3, 4])
# 输出: 10

📚 扩展阅读

想深入了解函数式编程思想?
点击此处查看《Python 函数式编程实战》

🧪 小练习

尝试用 mapfilter 实现:

  1. 将列表 [1, 2, 3, 4, 5] 中的每个元素平方后过滤出大于 10 的值
  2. 使用 reduce 计算 1+2+3+4+5 的乘积

答案可参考:Python 编程进阶 - 函数式编程