python 字符串转浮点数

论坛 期权论坛 脚本     
匿名技术用户   2020-12-22 20:02   26   0

http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317852443934a86aa5bb5ea47fbbd5f35282b331335000

利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456
rom functools import reduce

def str2float(s):

    def f(s):
        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.': '.'}[s]
    def g(x, y):
        return x*10 + y
    pos = s.find('.')
    front = reduce(g,map(f,s[0:pos]))
    rear = reduce(g,map(f,s[pos+1:]))/10**(len(s)-pos-1)
    return front+rear

print('str2float(\'123.456\') =', str2float('123.456'))
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP