map/reduce 练习

map (fun,L):传入两个参数,分别是一个函数名,一个可以迭代的数据集,功能是用fun函数处理每一个L中的元素,并返回一个数据集合(惰性,需要用list()转化)。

reduce(fun,L):传入两个参数,分别是一个函数名,一个可以迭代的数据集,功能是用fun函数一次处理L中两个连续元素,返回一个值。

map:

>>> def normalize(x):
    return x.capitalize()

>>> L1 = ['adam','LISA','barT']
>>> L2 = list(map(normalize,L1))
>>> print(L2)

reduce:

>>> from functools import reduce
>>> def fun(x,y):
    return x * y

>>> def prod(L):
    return reduce(fun,L)
>>> print(prod([3,5,7,9]))


联合使用:

>>> def str2float(s):
    return reduce(lambda x,y:x + int2dec(y),map(str2int,s.split('.')))

>>> def str2int(s):
    return reduce(lambda x,y:x * 10 + y,map(char2num,s))

>>> 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 int2dec(i):
    return i/(10**intLen(i))

>>> def intLen(i):
    return len('%d'%i)

>>> print(str2float('123.456'))

lambda是匿名函数,给出变量,计算函数

原文地址:https://www.cnblogs.com/dynas/p/6780214.html