python基礎,將str型別轉換為float型別
阿新 • • 發佈:2019-01-29
from functools import reduce
def str2float(s):
L=s.split('.');
def str2float(s):
L=s.split('.');
return reduce(lambda x,y:y+x*10,map(int,L[0]))+reduce(lambda x,y:y+x*10,map(int,L[1]))/10**len(L[1])
方法2:
from functools import reduce
def str2float(s):
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def char2num(s):
return DIGITS[s]
s=s.split('.') #split('.')將字串按‘.’分隔開
n=s[0]+s[1] #連線兩個字串,整體轉換
return reduce(lambda x,y:x10+y,map(char2num,n))/(10*len(s[1]))