函数式编程--高阶函数--map&reduce

定义

一个函数可以接受另一个函数作为参数,则被称为高阶函数

 

示例

函数add 接受参数 x,y,f  ,调用add时 参数 f 接受的是函数 abs

#一个简单的高阶函数,求两个参数的绝对值和

def add(x,y,f):
    return f(x)+f(y)

print(add(-5,-6,abs))

 

内置高阶函数-map

map函数接收两个参数,一个函数,一个 Iterable。 将参数函数作为于 Iterable的每一个元素,然后返回一个新的 Iterable。

示例:以下将求平方的函数传入map做参数,返回的list为每个值的平方结果

#内置高阶函数map的使用
def  f(x):
    return  x*x

list = [1,2,3,4,5,6,7,8,9,10]

list1=map(f,list)

print(list(list1))

 

内置高阶函数-reduce

reduce把一个函数作用在一个序列上[x1, x2, x3, ...] ,这个函数必须接受两个参数,reduce把结果继续和序列的下一个元素 做  累积计算。

其效果是 rudece(f,[x1,x2,x3,x4]) =  f( f( f(x1,x2) x3) x4)

示例

#reduce将序列[1,3,5,7,9]变为 13579
def fn(x,y):
    return x*10 + y

print(reduce(fn,[1,3,5,7,9]))

 

 

下面是对http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317852443934a86aa5bb5ea47fbbd5f35282b331335000 中三个练习题的作业 

1.

在下面方法,犯了一个比较窘的错误, name.capitalize()  ---> 错误的写为了 capitalize(name),报错  NameError: name 'capitalize' is not defined

#练习:将不规范的名称修改为首字符大写,其余小写的格式

from string import *
L1 = ['adam', 'LISA', 'barT'] def normalize(name): return name.capitalize() name=map(normalize,L1) print(list(name))

 

2.

#利用reduce函数传入一个list并求乘积
L2 =[1,3,5,7,9]

def prod(x,y):
    return x * y

print(reduce(prod,L2))

 

3.

#字符串转为整数,浮点数类型
def str2float(str):
    #获得分割后的str1,str2 ===》即 ‘123’,‘456’
    str1,str2=str.split('.' , 1)
    #{'1':1,'2':2}[s]是一个字典取值的写法。{'a':1,'b':2}是一个字典。[s]是key,类似于索引。
    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]
     
    def prod(x,y):
         return x*10+y

    # 将char2num作用于拼接后的字符串     
    numlist=list(map(char2num,str1+str2))

    str2num=reduce(prod,numlist)

    return  str2num*math.pow(10,-len(str2))

 

以上过程中搜索过的知识点:

字符串的分割:https://my.oschina.net/hkmax/blog/146553

字符串拼接:http://python3-cookbook.readthedocs.io/zh_CN/latest/c02/p14_combine_and_concatenate_strings.html

Python字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等):http://www.cnblogs.com/huangcong/archive/2011/08/29/2158268.html

math.pow 平方用法:http://www.runoob.com/python/func-number-pow.html

posted @ 2017-04-20 18:09  wangxy92  阅读(2056)  评论(0编辑  收藏  举报