高阶函数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 返回函数 匿名函数 装饰器 偏函数的更多相关文章

  1. Python学习:函数式编程(lambda, map() ,reduce() ,filter())

    1. lambda: Python 支持用lambda对简单的功能定义“行内函数” 2.map() : 3.reduce() : 4.filter() : map() ,reduce() , filt ...

  2. python--函数式编程 (高阶函数(map , reduce ,filter,sorted),匿名函数(lambda))

    1.1函数式编程 面向过程编程:我们通过把大段代码拆成函数,通过一层一层的函数,可以把复杂的任务分解成简单的任务,这种一步一步的分解可以称之为面向过程的程序设计.函数就是面向过程的程序设计的基本单元. ...

  3. [python基础知识]python内置函数map/reduce/filter

    python内置函数map/reduce/filter 这三个函数用的顺手了,很cool. filter()函数:filter函数相当于过滤,调用一个bool_func(只返回bool类型数据的方法) ...

  4. Python 函数式编程 & Python中的高阶函数map reduce filter 和sorted

    1. 函数式编程 1)概念 函数式编程是一种编程模型,他将计算机运算看做是数学中函数的计算,并且避免了状态以及变量的概念.wiki 我们知道,对象是面向对象的第一型,那么函数式编程也是一样,函数是函数 ...

  5. Python进阶:函数式编程(高阶函数,map,reduce,filter,sorted,返回函数,匿名函数,偏函数)...啊啊啊

    函数式编程 函数是Python内建支持的一种封装,我们通过把大段代码拆成函数,通过一层一层的函数调用,就可以把复杂任务分解成简单的任务,这种分解可以称之为面向过程的程序设计.函数就是面向过程的程序设计 ...

  6. (转)Python进阶:函数式编程(高阶函数,map,reduce,filter,sorted,返回函数,匿名函数,偏函数)

    原文:https://www.cnblogs.com/chenwolong/p/reduce.html 函数式编程 函数是Python内建支持的一种封装,我们通过把大段代码拆成函数,通过一层一层的函数 ...

  7. Python学习笔记系列——高阶函数(map/reduce)

    一.map #变量可以指向函数,函数的参数能接受变量,那么一个函数就可以接受另一个函数作为参数,这种函数被称之为高阶函数 def add(x,y,f): return f(x)+f(y) print( ...

  8. 【Python学习之六】高阶函数1(map、reduce、filter、sorted)

    1.map map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回.示例: >>> def ...

  9. Python学习笔记系列——高阶函数(filter/sorted)

    一.filter #filter()函数用于过滤序列.和map()类似,也接收一个函数和一个序列,把函数依次作用于每个元素,根据返回值是True还是False决定是否保留该元素. #filter()函 ...

随机推荐

  1. 契约式设计 契约式编程 Design by contract

    Design by contract - Wikipedia https://en.wikipedia.org/wiki/Design_by_contract What is the use of & ...

  2. and or 逻辑组合

    SELECT *  FROM ordertest_error_temp WHERE FROM_UNIXTIME(create_time,'%Y-%m-%d ')= CURDATE()AND( INST ...

  3. 【剑指offer】面试题42:单词翻转顺序&左右旋转字符串

    这里尽可能的不去用语言本身提供的函数. 将string逆置 def reverse(string): #return string[::-1] reversedStr = '' for i in xr ...

  4. ISA总线

    ISA总线: (Industry Standard Architecture:工业标准体系结构)是为PC/AT电脑而制定的总线标准,为16位体系结构,只能支持16位的I/O设备,数据传输率大约是16M ...

  5. [原创] [C#] 转换Excel数字列号为字母列号

    转换Excel数字列号为字母列号 例如: 0 -> A 26 -> AA private static string GetColumnChar(int col) { ; ; ) ) + ...

  6. YTU 2801: 用数字造数字(II)

    2801: 用数字造数字(II) 时间限制: 1 Sec  内存限制: 128 MB 提交: 244  解决: 168 题目描述 输入一个3位以上的整数,求其中最大的两个数字之和与最小的数字之和之间的 ...

  7. JavaScript 在浏览器环境中的模块管理

    如果需要,请自行复制下或下载列代码清单到本地运行(如果不修改源码,这些文件需要在同一目录 ,并且以下列文件名对应) 我只在Chrome浏览器中调试过(现在也没去处理浏览器兼容方面的问题)​1. 代码/ ...

  8. 【idea】idea快捷键

    Alt+回车 导入包,自动修正 alt+shift+↑  向上sout输出 psvm主函数 fori for Ctrl+N   查找类Ctrl+Shift+N 查找文件Ctrl+Alt+L  格式化代 ...

  9. Android控件之HorizontalScrollView 去掉滚动条

    在默认情况下,HorizontalScrollView控件里面的内容在滚动的情况下,会出现滚动条,为了去掉滚动条, 只需要在<HorizontalScrollView/>里面加一句 and ...

  10. shinx索引部分源码分析——过程:连接到CSphSource对应的sql数据源,通过fetch row取其中一行,然后解析出field,分词,获得wordhit,最后再加入到CSphSource的Hits里

    CSphSource 数据源 CSphSource_XMLPipe2-XML文件获取数据 CSphSource_SQL-SQL(MySQL)获取数据 CSphIndex 索引器 派生类CSphInde ...