從錯誤中學python(2)————字串轉浮點數

來源:互聯網
上載者:User

標籤:ack   lines   down   str   wiki   prompt   自己   構造   map   

題目

自己編寫函數:利用map和reduce編寫一個str2float函數,把字串’123.456’轉換成浮點數123.456:
題目來源——致敬廖雪峰

解決過程初步的解決方案
def str2float(s):    def char2num(s):        return {‘0‘:0,‘1‘:1,‘2‘:2,‘3‘:3,‘4‘:4,‘5‘:5,‘6‘:6,‘7‘:7,‘8‘:8,‘9‘:9}[s]    #這事實上是一個字典    index_point=s.find(‘.‘)    if index_point==-1:        daichu=1    else:        daichu=0.1**(len(s)-1-index_point)        s=s[0:index_point]+s[index_point+1:]#這裡是除去小數點    from functools import reduce    result1=reduce(lambda x,y:x*10+y,map(char2num,s))    return result1*daichu

這裡用到字串的find()函數進行模式比對。


這個看起來是沒有問題的可是python3.0裡面0.1的三次方是:

>>> 0.1**30.0010000000000000002

所以這樣不行,那麼我們就是用除法

改用除法
def str2float(s):    def char2num(s):        return {‘0‘:0,‘1‘:1,‘2‘:2,‘3‘:3,‘4‘:4,‘5‘:5,‘6‘:6,‘7‘:7,‘8‘:8,‘9‘:9}[s]    #這事實上是一個字典    index_point=s.find(‘.‘)    if index_point==-1:        daichu=1    else:        daichu=10**(len(s)-1-index_point)        s=s[0:index_point]+s[index_point+1:]#這裡是除去小數點    from functools import reduce    result1=reduce(lambda x,y:x*10+y,map(char2num,s))    return result1/daichu

這樣就能得到正確的結果了。

可是這裡我們使用find()函數還要用切片產生新的字串,這裡能夠用split()函數

def str2float(s):    def char2num(s):        return {‘0‘:0,‘1‘:1,‘2‘:2,‘3‘:3,‘4‘:4,‘5‘:5,‘6‘:6,‘7‘:7,‘8‘:8,‘9‘:9}[s]    #這事實上是一個字典    strs,index_point=s.split(‘.‘),len(s.split(‘.‘)[1])    daichu=10**index_point    s=strs[0]+strs[1]#這裡是除去小數點    from functools import reduce    result1=reduce(lambda x,y:x*10+y,map(char2num,s))    return result1/daichu

這裡的char2num事實上是全然不必要定義的,由於已經有int(str)這樣的建構函式了

改用int函數
def str2float(s):    strs,index_point=s.split(‘.‘),len(s.split(‘.‘)[1])    daichu=10**index_point    s=strs[0]+strs[1]#這裡是除去小數點    from functools import reduce    result1=reduce(lambda x,y:x*10+y,map(int,s))    return result1/daichu

當然我們也能夠把小數部分倒著計算,這樣代碼會更簡短。花更短的時間思考就能寫更短的代碼

小數部分倒著算
from functools import reducedef str2float(s):    a = s.split(‘.‘)    return reduce(lambda x, y: x*10+y, map(int, a[0]))           + reduce(lambda x, y: x/10+y, map(int, a[1][::-1])) / 10

a[1][::-1])這種方法非常巧妙。能夠用於把字串倒序輸出。比如
a[::-1]
也就是設定步長為1從右往左取,第二個參數表示右邊開始取的位置,第一個參數表示第一個不用取的位置。

從錯誤中學python(2)————字串轉浮點數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.