Pythonの高度な関数--map/reduce

5573 ワード

名前の最初の大文字の後ろに小文字を書きます.練習:
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'))