Python 高阶函数
来源:互联网 发布:emily the strange淘宝 编辑:程序博客网 时间:2024/05/24 01:18
高阶函数:一个函数可以接收另外一个函数作为参数,这个函数就称为高阶函数。
下面是高阶函数举例:
1、Map/Reduce
Map()接收两个参数,第一个参数是一个函数,第二参数是序列。第一个参数将作用到序列中的每一个元素,并将结果作为新的list返回。
>>> def f(x):... return x*x... >>> map(f,[1,2,3,4,5,6,7,8,9])[1, 4, 9, 16, 25, 36, 49, 64, 81]>>> map(str,[1,2,3,4])['1', '2', '3', '4']
Reduce()也接收两个参数,第一个为函数(这个函数必须接收两个参数),另外一个参数为序列,reduce把这个结果继续和序列中其它元素作为参数传到第一个参数函数里做处理。
[1, 3, 5, 7, 9]>>> nums=[1,2,3,4,5]>>> def add(x,y):... return x+y... >>> reduce(add,nums)15>>> def listToInt(x,y):... return x*10+y... >>> reduce(listToInt,[1,3,5,7,9])13579
2、filter
和Map/Reduce一样,filter()也接收两个参数,第一个参数为函数,第二个参数是序列。filter中传入的函数依次作用于序列中的每一个元素,根据返回值的是否为”True”,”False”来决定元素是否保留。
s='AppleGoogle'>>> def isLower(c):... return c>='a' and c<='z'... >>> filter(isLower,s)'ppleoogle'
3、sorted()
sorted()函数实现序列的排序,与上边的高阶函数不同的是sorted的第一个参数是序列,第二个参数是自定义的排序规则,第二个参数可以省略。
通常按照升序排列,对于两个元素x和y,如果x
>>> def reversed_cmp(x,y):... if x>y:... return -1... elif x<y:... return 1... return 0... >>> nums=[1,2,3,4,5]>>> sorted(nums,reversed_cmp)[5, 4, 3, 2, 1]
4、装饰器
def log(func): def wrapper(*args,**kw): print "call %s()",func.__name__ return func(*args,**kw) return wrapper@logdef now(): print "hello world!"now()print now.__name__
首先定义了一个log函数用于输出相关的信息,并在其内部定义wrapper函数,并然后wrapper函数。把@log
放在now函数的定义处,相当于执行了now=log(now),所以在函数的最后now的名字已经变为了wrapper。
输出:
call %s() nowhello world!wrapper
如果decorator需要传入参数,那么就需要编写一个返回decorator的函数
def log(text): def decorator(func): def wrapper(*args,**kw): print "%s %s()" %(text,func.__name__) return func(*args,**kw) return wrapper return decorator@log("execute")def now(): print "hello world"now()print now.__name__
执行结果:
execute now()hello worldwrapper
阅读全文
0 0
- python高阶函数
- python 高阶函数
- python高阶函数
- Python高阶函数
- python 高阶函数
- python高阶函数
- Python高阶函数
- python 高阶函数
- python 高阶函数
- python高阶函数
- python高阶函数
- python---高阶函数
- Python高阶函数
- Python 高阶函数
- python高阶函数
- python 高阶函数
- python 高阶函数
- python学习-高阶函数
- mysql触发器的实际应用
- java如何修改String中的一个字符
- HDU 6154 CaoHaha's staff(思维+找规律)
- 蓝桥杯 结点选择(树形dp)
- 只有五行的算法——多源最短路径 Floyd-Warshall
- Python 高阶函数
- 关于字符编码,你所需要知道的
- 多线程
- 【MOOC】【枚举】4.熄灯问题——位运算
- Laravel学习过程之基础知识学习和使用(三)
- J2EE中常用的名词解释
- ReactiveCocoa入门教程:第二部分
- Jenkins集成Maven代码覆盖率插件Cobertura
- C++多重继承范例