python-4函数式编程

1-高阶函数

   变量可以指向函数。   def add(x, y, f): 例如f参数为函数

       编写高阶函数,就是让函数的参数能够接收别的函数。

 Python内建了map()reduce()高阶函数。

  1.1 将list每项相乘

def f(x):
    return x*x
r = map(f, [1,2,3,4,5,6,7])
list(r) #[1, 4, 9, 16, 25, 36, 49] 每个变量的平方

1.2 把int转成字符串

list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])) #把int转成字符串

1.3 把str转换为int的函数:

from functools import reduce
def fn(x, y):
    return x * 10 + y
    
def char2num(s):
    digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    return digits[s]

print(reduce(fn, map(char2num, '13579')))把str转换为int的函数:

 1.4 filter使用

def not_empty(s):
    return s and s.strip()
list(filter(not_empty, ['A','B ','',None,'C','   ']))

1.5 sorted使用

print(sorted([1,22,33,21,8])) #默认排序
print(sorted(['a','Z','B','c'],key=str.lower)) #按小写排序
print(sorted(['a','Z','B','c'],key=str.lower,reverse=True)) #按小写反向排序

def my_Sorted(item):
    return item[0]
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
sorted(L,key=my_Sorted) #自定义的排序  

 1.6 闭包

def count():
    fs = []
    for i in range(1, 4):
        def f():
             return i*i
        fs.append(f)
    return fs

f1, f2, f3 = count() # 9 9 9     a,b,c = [1,2,3] #a=1,b=2,c=3

1.7 匿名函数  如: f= lambda x: x*x

list(map(lambda x: x*x, [1,2,3,4,5,6,7,8,9]))#[1, 4, 9, 16, 25, 36, 49, 64, 81]

1.8 装饰器 (装饰现有函数,返回一个新的函数。)

import functools
def log(func):
    @functools.wraps(func) #相当wrapper.__name__ = func.__name__
    def wrapper(*args,**kw):
        print("call %s():" % func.__name__);
        return func(*args, **kw)
    return wrapper
@log
def now():
    print('2018-05-11')
now() #相当 now = log(now)

     带参装饰器

import functools
def log1(text):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            print('%s %s:' % (text, func.__name__))
            return func(*args, **kw)
        return wrapper
    return decorator

@log1('exceue')    
def now1():
    print('2018-5-5')
now1() #now = log('execute')(now)
#我们来剖析上面的语句,首先执行log('execute'),返回的是decorator函数,
#再调用返回的函数,参数是now函数,返回值最终是wrapper函数。

1.9 偏函数(通过设定参数的默认值,可以降低函数调用的难度。而偏函数也可以做到这一点)

int('10111',base=2) #结果23, 以2进行进行转换

import functools
int2 = functools.partial(int, base=2)#自定义的偏函数
print(int2('10111')) #结果23,
原文地址:https://www.cnblogs.com/qinzb/p/9020551.html