Python 把字符串变成浮点数
生活随笔
收集整理的這篇文章主要介紹了
Python 把字符串变成浮点数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
from functools import reduce
di = {}
di.update(zip('1234567890.', [1,2,3,4,5,6,7,8,9,0,'.']))
def str2float(s):
st = s.split('.')
st1 = reduce(lambda x,y: 10*x + y, map(lambda x: di[x], st[0]))
try:
st2 = reduce(lambda x,y: (x*0.1 + y), map(lambda x: di[x], st[1][::-1]))/10
#st2 = reduce(lambda x,y: (x*0.1 + y), map(lambda x: di[x]/10, st[1][::-1])) ?#也可以在取數的時候變成一個一位小數
except:
st2=0
return st1 + st2
st = '123.456'
a = str2float(st)
print(a, type(a))
運行結果:
123.456 <class 'float'>
轉載于:https://www.cnblogs.com/guiyuhua/p/8641490.html
總結
以上是生活随笔為你收集整理的Python 把字符串变成浮点数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 洛谷.4234.最小差值生成树(LCT)
- 下一篇: 236. Lowest Common A