当前位置: 首页 > news >正文

python的高阶函数

1.定义

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

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

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

  2. 函数可以作为返回值

  3. 函数可以赋值给变量

2.map函数

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

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

# 将列表中的每个元素平方
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**2squared = list(map(square, numbers))

3.filter函数

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

# 过滤出偶数
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导入)。

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函数对可迭代对象进行排序。

# 按字符串长度排序
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.自定义高阶函数

# 函数作为参数
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 * factorreturn multiplierdouble = create_multiplier(2)
triple = create_multiplier(3)print(double(5))  # 10
print(triple(5))  # 15

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

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

def timer_decorator(func):"""计算函数执行时间的装饰器"""def wrapper(*args, **kwargs):import timestart = time.time()result = func(*args, **kwargs)end = time.time()print(f"{func.__name__} 执行时间: {end - start:.4f}秒")return resultreturn wrapper@timer_decorator
def slow_function():import timetime.sleep(1)return "完成"result = slow_function()  # 会自动打印执行时间

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

http://www.dtcms.com/a/403674.html

相关文章:

  • Python请求示例JD商品评论API接口,json数据返回
  • Json格式化处理碰到的问题
  • 驱动开发(4)|鲁班猫rk356x镜像编译,及启用SPI控制器驱动
  • Rust语言了解
  • 深圳成交型网站建设天元建设集团有限公司企业号
  • 织梦系统做的网站忘记登录密码semir是什么品牌
  • Python实现ETF网格自动化交易集成动量阈值判断
  • 使用c语言连接数据库
  • 网站在百度找不到了王占山人物简介
  • Windows Server 定时备份 MySQL 数据升级版:单表备份 + 压缩功能 + 运维统计
  • gpt-4o+deepseek+R生成热力图表
  • 管理系统前端模板河北seo网络推广
  • Mac完整Homebrew安装教程、brew安装教程踩过的坑、brew安装总结、安装brew遇到的问题
  • 想学做网站学那个软件好淘宝代运营公司排名
  • 网站建设策划怎么谈做视频网站用什么模板
  • 千秋网络是家西安做网站的公司安装免费下载app
  • P1073题解
  • ShardingSphere 分布式数据库中间件生态
  • 使用时长提升 4 倍,融云 AI Agent 助力中东语聊应用激活新用户
  • 旅行商问题以及swap-2opt应用
  • 【知识图谱:实战篇】--搭建医药知识图谱问答系统
  • shell编程:sed - 流编辑器(3)
  • 建站最便宜的平台免费网络app
  • 《第四届数字信任大会》精彩观点:腾讯经验-人工智能安全风险之应对与实践|从十大风险到企业级防护架构
  • StarRocks 助力印度领先即时零售平台 Zepto 构建实时洞察能力
  • 法制教育网站制作伪装网站
  • cgdb 学习笔记(GDB 图形化增强工具)
  • 广州专门做网站企业网站制作公司排名
  • .h264或.264视频文件转化成mp4视频
  • 【Python】正则表达式