python-高阶函数

map函数

map(func, Iterable) , 返回一个Iterable的map对象


reduce函数

reduce(func,Iterable), 将后面可迭代对象的每个元素都作用于函数(函数必须接收两个参数),结果在和序列的下一个元素计算

from functools import reduce
a = reduce(lambda x,y: x+y, [1,2,3,4,5,6])
print(a)

21

filter函数

filter(func, Iterable), 用于过滤序列

list(filter(lambda x: x and x.strip(), ['a','b','']))  #返回一个序列中非空的字符串

['a','b']
help(str.strip)
strip(...)
    S.strip([chars]) -> str
    
    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.

sorted函数

sorted(list, key=xxx),用于排序,key可以为函数

sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)

['about', 'bob', 'Credit', 'Zoo']    #排序时无视首字母大小写


L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def byname(a):
    return a[0]
def byscore(a):
    return a[1]
sorted(L,key=byname)   #按名字首字母排序
sorted(L,key=byname)   #按分数高低排序

装饰器

decorator是一个返回函数的高阶函数

import time
a = '%X'
def log(func):
    def wrapper(*args, **kw):
        print('call %s():' % func.__name__)
        return func(*args, **kw)
    return wrapper

@log
def now()
    print(time.strftime(a, time.localtime()))

偏函数

functools.partial创建一个偏函数的,直接创建一个新的函数int2:

import functools
int2 = functools.partial(int, base=2)
int2('1000000')

posted on 2016-11-28 15:36  胡欣欣  阅读(248)  评论(0编辑  收藏  举报