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']
相关推荐
孟陬2 分钟前
Foobar 技术周刊 #161:AI 录屏员工屏幕训练 SOP,被当做「动物园的猴子」是否触犯隐私?
前端·后端·程序员
SimonKing13 分钟前
又一款数据库同步神器,2.3K Star的dbswitch
java·后端·程序员
1-1=016 分钟前
Vue 混入(Mixin)和 2.插件 (Plugins)
前端·vue.js
CoderYanger24 分钟前
Java EE 进阶:11. SpringBoot 统一功能处理(第二弹):DispatcherServlet 源码分析+适配器模式
java·数据库·hive·spring boot·面试·java-ee·mybatis
BD_Marathon35 分钟前
Jupyter魔法命令
ide·python·jupyter
-梅35 分钟前
linux(番外)线程,锁,条件变量封装;日志与线程池
linux·c语言·前端·c++
词却1 小时前
Python 正则表达式实战:使用 re 模块提取符合条件的字符串
python·正则表达式
Rain的Java大神之路1 小时前
前端转 Java 全栈:用 AI 两天交付一个能跑的 Demo,踩坑全记录
java·前端·后端
星落梦生1 小时前
Tlias前端案例涉及知识点 (14)
开发语言·前端·javascript
汤姆宝库2 小时前
视觉语言模型的实现:LLaVA式投影与指令微调
python·深度学习·语言模型