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函数式编程的重要组成部分,熟练掌握它们可以写出更加优雅和高效的代码。

相关推荐
孟健3 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞4 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽7 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程11 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪11 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook12 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python