python的高阶函数

1.定义

高阶函数(Higher-order Function)是指能够接受其他函数作为参数,或者将函数作为返回值的函数。在Python中,函数是一等公民(First-class Citizen),这意味着函数可以像其他数据类型一样被传递和使用。

高阶函数有以下三个特征:

  1. 函数可以作为参数传递

  2. 函数可以作为返回值

  3. 函数可以赋值给变量

2.map函数

map(function, iterable) 将函数应用于可迭代对象的每个元素,返回一个迭代器。

其中lambda是匿名函数。在此处代表一个任意函数。

python 复制代码
# 将列表中的每个元素平方
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # [1, 4, 9, 16, 25]

# 使用普通函数
def square(x):
    return x**2

squared = list(map(square, numbers))

3.filter函数

filter(function, iterable) 根据函数的返回值(True/False)来过滤元素。

python 复制代码
# 过滤出偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # [2, 4, 6, 8, 10]

# 过滤出长度大于3的字符串
words = ["apple", "cat", "dog", "elephant"]
long_words = list(filter(lambda word: len(word) > 3, words))
print(long_words)  # ["apple", "elephant"]

4.reduce函数

reduce(function, iterable[, initializer]) 对可迭代对象中的元素进行累积计算(需要从functools导入)。

python 复制代码
from functools import reduce

# 计算乘积
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # 120

# 找出最大值
max_value = reduce(lambda x, y: x if x > y else y, numbers)
print(max_value)  # 5

5.sorted函数

sorted(iterable, key=None, reverse=False) 根据key函数对可迭代对象进行排序。

python 复制代码
# 按字符串长度排序
words = ["apple", "cat", "dog", "banana"]
sorted_words = sorted(words, key=len)
print(sorted_words)  # ['cat', 'dog', 'apple', 'banana']

# 按第二个字符排序
sorted_by_second = sorted(words, key=lambda x: x[1])
print(sorted_by_second)  # ['banana', 'cat', 'apple', 'dog']

6.自定义高阶函数

python 复制代码
# 函数作为参数
def apply_twice(func, value):
    """将函数应用两次"""
    return func(func(value))

result = apply_twice(lambda x: x * 2, 3)
print(result)  # 12 (3*2=6, 6*2=12)

# 函数作为返回值
def create_multiplier(factor):
    """创建一个乘法器函数"""
    def multiplier(x):
        return x * factor
    return multiplier

double = create_multiplier(2)
triple = create_multiplier(3)

print(double(5))  # 10
print(triple(5))  # 15

上述代码分别是函数作为参数 和函数作为返回值的两种情况。

现在掌握了如何自定义高阶函数后,结合装饰器@使用以下:

python 复制代码
def timer_decorator(func):
    """计算函数执行时间的装饰器"""
    def wrapper(*args, **kwargs):
        import time
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} 执行时间: {end - start:.4f}秒")
        return result
    return wrapper

@timer_decorator
def slow_function():
    import time
    time.sleep(1)
    return "完成"

result = slow_function()  # 会自动打印执行时间

最后,高阶函数是Python函数式编程的重要组成部分,熟练掌握它们可以写出更加优雅和高效的代码。

相关推荐
§ꦿCFོ༉7 小时前
嵌入式八股文—C语言入门学习(四)
c语言·开发语言·学习
投图匠8 小时前
十种不同风格的 CTP接口 框架
开发语言·python
2601_967980119 小时前
深入理解词向量算法及其在Python中的实践
python·word2vec·glove·fasttext·词向量
129Lab10 小时前
电池循环测试数据自动化分析:用Python+AI工具构建一键式寿命评估流水线
python·数据分析·电池测试·数据自动化·寿命评估
treasure14010 小时前
【复古】浅尝Django前后端不分离
前端·css·python·django·bootstrap·html·web
Dmz丶11 小时前
前端转 AI 100 天 Day 44:前端集成实战——用 React 给 Agent 做个正式界面
python
jay神11 小时前
基于 YOLOv8 的手势识别系统(Web 版)
前端·人工智能·python·深度学习·yolo·计算机视觉·计算机毕业设计
DeepVisionary11 小时前
阿里云上线旗舰多模态新模型,不公布跑分且限时14天退役
python·自动化
东莞市云毅网络有限公司11 小时前
FAQ 覆盖度打分:TF-IDF 与向量嵌入双路召回的 Python 实现
python·数据清洗·rag·企业知识库·文档解析
爱笑的k1111 小时前
nano-vllm 源码剖析:千行 Python 手写离线推理引擎的调度、显存与并行时序
开发语言·python·vllm