版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w144215160044/article/details/79887762
利用map
和reduce
编写一个str2float
函数,把字符串'123.456'
转换成浮点数123.456
:
第一次接触map和reduce,不太了解此代码的实现,参考了网上大神的讲解
1.新函数的用法index(),表示获取制定字符在字符串中的位置
2.**表示次方
>>> from functools import reduce
>>> def str2float(s):
def multiple(x, y):
return x * 10 + y
id = s.index('.')
L1 = list(map(int, [x for x in s[:id]]))
L2 = list(map(int, [x for x in s[id+1:]]))
return reduce(multiple, L1) + reduce(multiple, L2)/10**len(L2)
>>> print(str2float('123.45'))
输出:123.45