剛摸Python三天,看教程有個練習 “利用map和reduce撰寫一個str2float函式,把字串'123.456'轉換成浮點數123.456”
下面是我的代碼:
from functools import reduce
def str2float(f):
def to_float(x):
df = {'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'0':0}
return df[x]
def c10(x,y=0):
return x * 10 + y
def d10(z,k):
m = z*0.1+k*0.1
return m
d = 0
for s in f:
if s=='.':
i_ = f[:d]
f_ = f[d+1:]
f_ ='0'+f_[::-1]
d = d + 1
ii = reduce(c10,map(to_float,i_))
ff = reduce(d10,map(to_float,f_))
return ii+ff
結果:
Python 3.7.3 (default, Apr 3 2019, 05:39:12)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from one import str2float
>>> str2float('101.123')
101.123 <--這種正常
>>> str2float('0.123')
0.12300000000000001 <--這種非正常
>>> str2float('1.123')
1.123
>>> str2float('1.00123')
1.00123
>>> str2float('0.00123')
0.0012300000000000002 <--這種非正常
>>>
這是哪里錯了?
還有,這代碼還有更好的寫法嗎?
謝謝了!
uj5u.com熱心網友回復:
這是Python自帶bug,消除不了
uj5u.com熱心網友回復:
直接Decimal就挺好。uj5u.com熱心網友回復:
沒必要這么麻煩,本身python就自帶這樣的函式,num輸出就是小數
from decimal import *
s = '1.231'
num = Decimal(s)
print(type(num))
uj5u.com熱心網友回復:
1. 直接用 float 函式:print(float('123.45'))2. 直接用 eval 函式:
print(eval('123.45'))3. 一定要練習用reduce和map也可以啊,有點牛刀 殺雞的感覺:
from functools import reduce
def str2float(f):
s = f.split('.')
s1 = list(s[0])
s2 = list(s[1])
s2.reverse()
s2.append('0')
to_digit = lambda x: int(x)
c10 = lambda x,y: x*10+y
d10 = lambda x,y: x*0.1 + y
ii = reduce(c10, map(to_digit, s1))
ff = reduce(d10, map(to_digit, s2))
return ii+ff
print(str2float('123.45'))
uj5u.com熱心網友回復:
問題是float的精度問題單精度浮點只有十進制6位多的精度
uj5u.com熱心網友回復:
from functools import reducefrom decimal import Decimal
s = input('請輸入字串:')
def str2float(f):
def to_float(x):
df = {'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'0':0}
return df[x]
def c10(x,y=0):
return x * 10 + y
def d10(z,k):
tmp1 = Decimal(str(z))*Decimal(str(0.1))
tmp2= Decimal(str(k))*Decimal(str(0.1))
m = Decimal(str(tmp1)) + Decimal(str(tmp2))
return m
i_ = f.split('.',1)[0]
f_ = f.split('.',1)[1]
f_ = '0' + f_[::-1]
ii = reduce(c10,map(to_float,i_))
ff = reduce(d10,map(to_float,f_))
return ii+ff
print(str2float(s))
uj5u.com熱心網友回復:
牛B,你這就是某些人常說的:要從不斷摸索中吸取深刻教訓,舉一反三、全面整改
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/11730.html
上一篇:Python
