from functools import reducedef str2float(S): if not isinstance(S, str): raise TypeError('参数类型必须是str') digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.':-1} def char2num(S): return digits[S] nums = list(map(char2num, S)) point = 0 def fn(x, y): nonlocal point if y == -1: point = 1 return x if point == 0: return x * 10 + y else: point = point * 10 return x + y / point return reduce(fn, nums)
Superman灬code
1.名字转换
def normalize(name):
name = name[0].upper() + name[1:].lower()
return name
2.乘法运算
from functools import reduce
def Multiply(x, y):
return x * y
def prod(L):
if not isinstance(L, Iterable):
raise TypeError('参数必须是Iterable')
return reduce(Multiply, L)
3.str转换成float