python中的高阶函数

1、什么是高阶函数?

高阶函数是指将函数作为参数传入。就是高阶函数

2、高阶函数有哪些?

map 映射函数

python 复制代码
>>> print(list(map(lambda x:x*x,range(1,11))))
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> print(list(map(lambda x:str(x),[1,2,3,4,5])))
['1', '2', '3', '4', '5']
>>>

filter 过滤函数

python 复制代码
>>> print(list(filter(lambda x:x%3==0,range(1,101))))
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
>>> print(list(filter(lambda x:x %2 == 0,range(1,11))))
[2, 4, 6, 8, 10]
>>> print(list(filter(lambda x:x%2,range(1,11))))
[1, 3, 5, 7, 9]
>>> 

reduce 函数累积求值(需要导入from functools import reduce)

python 复制代码
>>> n = [1,2,3,4,5,6,7]
>>> from functools import reduce
>>> print(reduce(lambda n,y:n*y,n))
5040

sorted 排序函数

python 复制代码
>>> list1=[7, -8, 5, 4, 0, -2, -5]
>>> print(sorted(list1,key=lambda x:max(list1)-x+1 if x <=0 else x))
[4, 5, 7, 0, -2, -5, -8]
>>> print(list(sorted(list1,key=lambda x:(x<=0,abs(x)))))
[4, 5, 7, 0, -2, -5, -8]
>>> 
>>> list1 = ['bob','about','Zoo','Credit']
>>> print(sorted(list1,key=lambda x:x.lower()))
['about', 'bob', 'Credit', 'Zoo']
相关推荐
艾莉丝努力练剑12 小时前
【C++:异常】C++ 异常处理完全指南:从理论到实践,深入理解栈展开与最佳实践
java·开发语言·c++·安全·c++11
武子康12 小时前
Java-184 缓存实战:本地缓存 vs 分布式缓存(含 Guava/Redis 7.2)
java·redis·分布式·缓存·微服务·guava·本地缓存
小马爱打代码18 小时前
Spring Boot:模块化实战 - 保持清晰架构
java·spring boot·架构
遇到困难睡大觉哈哈18 小时前
Harmony os 静态卡片(ArkTS + FormLink)详细介绍
前端·microsoft·harmonyos·鸿蒙
程序员小远18 小时前
软件测试之单元测试详解
自动化测试·软件测试·python·测试工具·职场和发展·单元测试·测试用例
小坏讲微服务19 小时前
SpringBoot4.0整合knife4j 在线文档完整使用
java·spring cloud·在线文档·knife4j·文档·接口文档·swagger-ui
8***Z8919 小时前
springboot 异步操作
java·spring boot·mybatis
i***132419 小时前
Spring BOOT 启动参数
java·spring boot·后端
用户479492835691519 小时前
Bun 卖身 Anthropic!尤雨溪神吐槽:OpenAI 你需要工具链吗?
前端·openai·bun
坚持不懈的大白19 小时前
后端:SpringMVC
java