廖雪峰 map/reduce 模块中的练习题https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317852443934a86aa5bb5ea47fbbd5f35282b331335000#0
练习
1.利用map()
函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT']
,输出:['Adam', 'Lisa', 'Bart']
:
1 def normalize(name): 2 mystr =[] 3 if len(name)>0: 4 mystr.append(name[0].upper()) 5 name= name[1:] 6 for char in name: 7 mystr.append(char.lower()) 8 return ''.join(mystr) 9 L1 = ['adam', 'LISA', 'barT'] 10 L2 = list(map(normalize, L1)) 11 print(L2)
2.python提供的sum()
函数可以接受一个list并求和,请编写一个prod()
函数,可以接受一个list并利用reduce()
求积:
1 from functools import reduce 2 def prod(L): 3 def fn(x,y): 4 return x*y 5 return reduce(fn,L) 6 print('3*5*7*9=%d'%prod([3,5,7,9]))
3.利用map
和reduce
编写一个str2float
函数,把字符串'123.456'
转换成浮点数123.456
:
备注:大神的代码
1 from functools import reduce 2 def str2float(s): 3 def fn(x,y): 4 return x*10+y 5 n = s.index('.') 6 s1 = list(map(int,[x for x in s[:n]])) 7 s2 = list(map(float,[x for x in s[n+1:]])) 8 return reduce(fn,s1) + reduce(fn,s2)/10**len(s2) 9 print('123.4567=%.4f'%str2float('123.4567'))