Python学习 Day 5 高阶函数 map/reduce filter sorter 返回函数 匿名函数 装饰器 偏函数
2015-04-25 23:03
1136 查看
高阶函数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的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单。
求关注 求扩散
变量可以指向函数
>>> 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进阶:函数式编程(高阶函数,map,reduce,filter,sorted,返回函数,匿名函数,偏函数)...啊啊啊
- Python 函数式编程(高阶函数、把函数作为参数、map()函数、reduce()函数、filter()函数、自定义排序函数、函数返回函数、闭包、匿名函数、装饰器decorator)
- Python函数式编程(高阶函数 <map/reduce filter sorted> 返回函数 匿名函数 装饰器 偏函数)
- Python入门 第四天(函数式编程、map、reduce、filter、排序函数、函数返回函数、闭包、匿名函数lambda)
- Python高阶函数(Map、Reduce、Filter)和lambda函数一起使用 ,三剑客
- python 高阶函数 map reduce filter sorted 闭包 装饰器
- 13 python装饰器,函数对象以及一些高阶函数如map/reduce,匿名函数,返回函数,偏函数等等
- Python小白学习之路(十五)—【map()函数】【filter()函数】【reduce()函数】
- 【语言工具】Python闭包,装饰器,生成器,偏函数,函数式编程,lamda,map,reduce,filter
- Python教程学习简记8--Python 高阶函数 map/reduce filter sorted
- python学习笔记,返回函数,匿名函数,装饰器
- python 的 map(),reduce(),filter(),返回函数,闭包
- python学习(9)高阶函数map、reduce、filter、sorted
- python几个重要的函数(lambda,filter,reduce,map,zip) 一、匿名函数lambda lambda argument1,argument2,...argumentN :e
- Python中高阶函数 map(),reduce(),filter()学习
- python中的lambda匿名函数以及针对序列的内建函数map、filter和reduce
- Python学习2--高阶函数map、reduce、filter、sorted
- Python学习3--返回函数 、匿名函数、装饰器、偏函数
- python--函数式编程 (高阶函数(map , reduce ,filter,sorted),匿名函数(lambda))
- python中map、reduce、filter、自定义排序函数、装饰器函数和偏函数