名字开头大写 后面小写;练习:
def normalize(name):
return name[0].upper() + name[1:].lower()
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
reduce求积:
from functools import reduce def prod(L):
def fn(x, y):
return x * y
return reduce(fn, L)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
reduce
把结果继续和序列的下一个元素做累积计算
字符串转浮点数练习:
from functools import reduce def str2int(s):
def char2num(c):
return {'': 0, '': 1, '': 2, '': 3, '': 4, '': 5, '': 6, '': 7, '': 8, '': 9}[c]
return reduce(lambda x, y: x *10 + y, map(char2num, s)) def str2float(s):
s_list = s.split('.')
float_i = str2int(s_list[0]) #
float_f = str2int(s_list[1]) / (10**len(s_list[1])) #456/1000
return float_i + float_f
print('str2float(\'123.456\') =', str2float('123.456'))