Python高级函数--map/reduce

名字开头大写 后面小写;练习:

1 def normalize(name):
2     return name[0].upper() + name[1:].lower()
3 L1 = ['adam', 'LISA', 'barT']
4 L2 = list(map(normalize, L1))
5 print(L2)

reduce求积:

1 from functools import reduce
2 
3 def prod(L):
4     def fn(x, y):
5         return x * y
6     return reduce(fn, L)
7 print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))

reduce把结果继续和序列的下一个元素做累积计算

字符串转浮点数练习:

 1 from functools import reduce
 2 
 3 def str2int(s):
 4     def char2num(c):
 5         return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[c]
 6     return reduce(lambda x, y: x *10 + y, map(char2num, s))
 7 
 8 def str2float(s):
 9     s_list = s.split('.')
10     float_i = str2int(s_list[0]) #123
11     float_f = str2int(s_list[1]) / (10**len(s_list[1])) #456/1000
12     return float_i + float_f
13 print('str2float(\'123.456\') =', str2float('123.456'))

 

你可能感兴趣的:(Python高级函数--map/reduce)