前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python学习 Day 5 高阶函数 map/reduce filter sorter 返回函数 匿名函数 装饰器 偏函数

Python学习 Day 5 高阶函数 map/reduce filter sorter 返回函数 匿名函数 装饰器 偏函数

作者头像
统计学家
发布2019-04-10 16:54:58
3180
发布2019-04-10 16:54:58
举报

高阶函数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的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单。

求关注 求扩散

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2015-04-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 机器学习与统计学 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档