Python3学习笔记07——map和reduce的使用

#利用map()函数,把用户输入的不规范名字,变为规范名字(首字母大写,其他小写)

def normalize(name):
    name=name[0].upper()+name[1:].lower()
    return name

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

#编写一个prod()函数,可以接受一个List并礼用reduce()求积

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

def prod(s):
    return reduce(ji,s)

print(prod([3,5,7,9]))

#利用map和reduce编写一个str2float函数,把字符串‘123.456’转换成浮点数123.456:

from functools import reduce

def str2float(s):
    def str2num(s):
        return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7
                ,'8':8,'9':9}[s]
    def fnMuti(x,y):
        return x*10+y
    def fnDivid(x,y):
        return x/10+y
    dotIndex = s.index('.')
    return reduce(fnMuti,map(str2num,s[:dotIndex]))+reduce(fnDivid,list(map(str2num,s[dotIndex+1:]))[::-1])/10

print(str2float('123.456'))

注意:
[][::-1] list的逆置

map() 返回的是map,需要转换成list

你可能感兴趣的:(python基础)