#练习1: 利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。 # 输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']: ''' def normalize(name): list = [] for i, x in enumerate(name): if i == 0: list.append(x.upper()) else: list.append(x.lower()) return ''.join(list) L1 = ['adam', 'LISA', 'barT'] L2 = list(map(normalize, L1)) print(L2) ''' #练习2:Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积: ''' from functools import reduce def prod(L): def f(a, b): return a*b x = reduce(f, L) return x print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9])) if prod([3, 5, 7, 9]) == 945: print('测试成功!') else: print('测试失败!') ''' #练习3: 利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456: ''' from functools import reduce def str2float(s): def f(x): d = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} return d[x] def get_integer(a, b): return a*10 + b point = 1 def get_decimal(a, b): nonlocal point point *= 10; return a + b/point; list = str(s).split('.') ans1 = reduce(get_integer, map(f, list[0])) # 求整数部分 ans2 = reduce(get_decimal, map(f, list[1]), 0.0) # 求小数部分 return ans1+ans2 print('str2float(\'123.456\') =', str2float('123.456')) if abs(str2float('123.456') - 123.456) < 0.00001: print('测试成功!') else: print('测试失败!') '''
廖雪峰map/reduce学习的三个小练习
猜你喜欢
转载自blog.csdn.net/wangzhuo0978/article/details/79835209
今日推荐
周排行