Python学习 Day 5 高阶函数 map/reduce filter sorter 返回函数 匿名函数 装饰器 偏函数
高阶函数Higher-orderfunction
变量可以指向函数
>>> abs #abs(-10)是函数调用,而abs是函数本身
<built-in function abs>
>>> f = abs #函数本身也可以赋值给变量
>>> f #变量可以指向函数
<built-in function abs>
>>> f(-10) #变量调用函数
10
函数名也是变量
>>> abs = 10
>>> abs(-10) #把abs指向10后,无法通过abs(-10)调用该函数
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
传入函数
既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
>>> def add(x, y, f):
return f(x) + f(y)
>>> add(-1,-2,abs)
map
map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。举例说明,比如我们有一个函数f(x)=x2,要把这个函数作用在一个list [1, 2, 3, 4, 5, 6, 7, 8, 9]上,就可以用map()实现如下:
>>> def f(x):
return x * x
>>> map(f, [1, 2, 3, 4, 5, 6, 7,8, 9]) #第一个参数是f,即函数对象本身
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> map(str, [1, 2, 3, 4, 5, 6, 7,8, 9]) #把这个list所有数字转为字符串
['1', '2', '3', '4', '5', '6', '7', '8','9']
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of asequence,from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates((((1+2)+3)+4)+5). If initial ispresent, it is placed before the items of the sequence in the calculation, and serves as a default whenthe sequence is empty.
>>> def add(x, y):
return x + y
>>> reduce(add, [1, 3, 5, 7, 9])
25
def str2int(s):#把str转换为str2int
def fn(x, y):
return x * 10 + y
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7,'8': 8, '9': 9}[s]
return reduce(fn, map(char2num, s))
filter
filter(...)
filter(function or None, sequence) -> list, tuple, or string
Return those items of sequence for which function(item) is true. If
function is None, return the items that are true. If sequence is a tuple
or string, return the same type, else return a list.
def is_odd(n):#list中,删掉偶数
return n % 2 == 1
filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
def not_empty(s):#序列中的空字符串删掉
return s and s.strip()
filter(not_empty, ['A', '', 'B', None, 'C',' '])
sorted
sorted(iterable, cmp=None, key=None,reverse=False) --> new sorted list
>>> def reversed_cmp(x, y):#倒序排序
if x > y:
return -1
if x < y:
return 1
return 0
>>> sorted([36, 5, 12, 9, 21],reversed_cmp)
[36, 21, 12, 9, 5]
>>> def cmp_ignore_case(s1, s2):#忽略大小写来比较两个字符串
u1 = s1.upper()
u2 = s2.upper()
if u1 < u2:
return -1
if u1 > u2:
return 1
return 0
>>> sorted(['bob', 'about', 'Zoo','Credit'], cmp_ignore_case)
['about', 'bob', 'Credit', 'Zoo']
返回函数
def calc_sum(*args):#可变参数的求和
ax = 0
for n in args:
ax = ax + n
return ax
不需要立刻求和,而是在后面的代码中,根据需要再计算.
def lazy_sum(*args):
def sum():#又定义了函数sum
ax = 0
for n in args:
ax = ax + n#引用外部函数lazy_sum的参数和局部变量
return ax#这种程序结构称为“闭包
return sum
>>> f = lazy_sum(1, 3, 5, 7, 9)
>>> f
<function sum at 0x10452f668>
>>> f()
25
>>> f1 = lazy_sum(1, 3, 5, 7, 9)
>>> f2 = lazy_sum(1, 3, 5, 7, 9)
>>> f1==f2#每次调用都会返回一个新的函数,结果互不影响
False
匿名函数
>>> map(lambda x: x * x, [1, 2, 3,4, 5, 6, 7, 8, 9])
[1, 4, 9, 16, 25, 36, 49, 64, 81]
匿名函数lambda x: x * x实际上就是:
def f(x):
return x * x
>>> f = lambda x: x * x#把匿名函数赋值给一个变量,再利用变量来调用该函数
>>> f
<function <lambda> at0x10453d7d0>
>>> f(5)
25
装饰器
decorator就是一个返回函数的高阶函数。所以,我们要定义一个能打印日志的decorator,可以定义如下:
def log(func):#decorator
def wrapper(*args, **kw):
print 'call %s():' % func.__name__
return func(*args, **kw)
return wrapper
@log#把decorator置于函数的定义处
def now():
print '2013-12-25'
>>> now()
call now():#运行now()函数前打印一行日志
2013-12-25
def log(text):#自定义log的文本
def decorator(func):
def wrapper(*args, **kw):
print '%s %s():' % (text,func.__name__)
return func(*args, **kw)
return wrapper
return decorator
@log('execute')#3层嵌套的decorator用法
def now():
print '2013-12-25'
偏函数Partial function
>>> int('12345', base=8)#传入base参数,就可以做N进制的转换
5349
def int2(x, base=2):#定义int2()函数,默认把base=2传进去
return int(x, base)
>>> int2('1000000')
64
functools.partial就是帮助我们创建一个偏函数的,不需要我们自己定义int2(),可以直接使用下面的代码创建一个新的函数int2:
>>> import functools
>>> int2 = functools.partial(int,base=2)
>>> int2('1000000')
64
functools.partial的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单。
求关注 求扩散
Python学习 Day 5 高阶函数 map/reduce filter sorter 返回函数 匿名函数 装饰器 偏函数的更多相关文章
- Python学习:函数式编程(lambda, map() ,reduce() ,filter())
1. lambda: Python 支持用lambda对简单的功能定义“行内函数” 2.map() : 3.reduce() : 4.filter() : map() ,reduce() , filt ...
- python--函数式编程 (高阶函数(map , reduce ,filter,sorted),匿名函数(lambda))
1.1函数式编程 面向过程编程:我们通过把大段代码拆成函数,通过一层一层的函数,可以把复杂的任务分解成简单的任务,这种一步一步的分解可以称之为面向过程的程序设计.函数就是面向过程的程序设计的基本单元. ...
- [python基础知识]python内置函数map/reduce/filter
python内置函数map/reduce/filter 这三个函数用的顺手了,很cool. filter()函数:filter函数相当于过滤,调用一个bool_func(只返回bool类型数据的方法) ...
- Python 函数式编程 & Python中的高阶函数map reduce filter 和sorted
1. 函数式编程 1)概念 函数式编程是一种编程模型,他将计算机运算看做是数学中函数的计算,并且避免了状态以及变量的概念.wiki 我们知道,对象是面向对象的第一型,那么函数式编程也是一样,函数是函数 ...
- Python进阶:函数式编程(高阶函数,map,reduce,filter,sorted,返回函数,匿名函数,偏函数)...啊啊啊
函数式编程 函数是Python内建支持的一种封装,我们通过把大段代码拆成函数,通过一层一层的函数调用,就可以把复杂任务分解成简单的任务,这种分解可以称之为面向过程的程序设计.函数就是面向过程的程序设计 ...
- (转)Python进阶:函数式编程(高阶函数,map,reduce,filter,sorted,返回函数,匿名函数,偏函数)
原文:https://www.cnblogs.com/chenwolong/p/reduce.html 函数式编程 函数是Python内建支持的一种封装,我们通过把大段代码拆成函数,通过一层一层的函数 ...
- Python学习笔记系列——高阶函数(map/reduce)
一.map #变量可以指向函数,函数的参数能接受变量,那么一个函数就可以接受另一个函数作为参数,这种函数被称之为高阶函数 def add(x,y,f): return f(x)+f(y) print( ...
- 【Python学习之六】高阶函数1(map、reduce、filter、sorted)
1.map map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回.示例: >>> def ...
- Python学习笔记系列——高阶函数(filter/sorted)
一.filter #filter()函数用于过滤序列.和map()类似,也接收一个函数和一个序列,把函数依次作用于每个元素,根据返回值是True还是False决定是否保留该元素. #filter()函 ...
随机推荐
- mac下破解apk文件以及apktool的相关使用
Android apktool是一个用来处理APK文件的工具,可以对APK进行反编译生成程序的源代码和图片.XML配置.语言资源等文件,也可以添加新的功能到APK文件中.用该工具来汉化Android软 ...
- linux怎么区别文本文件和二进制文件
linux的文本文件与二进制文件的区分与windows的区分是相同的!说到底计算机存储的文件都是以二进制形式存储的,但是区别是,习惯上认为: (1).文本文件 文本文件是包含用户可读信息的文件.这些文 ...
- HDU1054 Strategic Game —— 最小点覆盖 or 树形DP
题目链接:https://vjudge.net/problem/HDU-1054 Strategic Game Time Limit: 20000/10000 MS (Java/Others) ...
- try-with-resources使用示例
try (InputStream is = new FileInputStream("test")) { is.read(); ... } catch(Exception e) { ...
- C#函数3递归
using System;using System.Collections.Generic;using System.Linq;using System.Text; namespace Console ...
- 性能-发挥ORACLE分区表
ORACLE分区表发挥性能 http://www.cnblogs.com/zwl715/p/3962837.html 1.1 分区表PARTITION table 在ORACLE里如果遇到特别大的表, ...
- node 中mongoose使用validate和密码加密的问题
在今天一直被一个问题困扰,就算是使用mongoose的alidate的时候想要限制密码的位数,比如不能少于几位,但是一直出错. 最后发现原来使用validate的时候,是在数据将要存入数据库的时候,因 ...
- 简单粗暴解决google被和谐导致google fonts无法加载的问题
原文:http://www.v2ex.com/t/118403 解决方法:fonts.googleapis.com替换为fonts.useso.com, fonts.useso.com是360安全卫士 ...
- hdu4815 概率问题
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4815 好久没写dp了..最开始题意都理解错了, 哎!!我现在很饿也很困!! AC代码: #includ ...
- 线程Coroutines 和 Yield(转)
之前一直很纠结这个问题,在网上找到了这篇文章,给大家分享下: 第一种方法: void Start() { print("Starting " + Ti ...