1 #利用map和reduce編寫一個str2float函數,把字符串'123.456'轉換成浮點數123.456:python
代碼:ide
2 3 from functools import reduce 4 str = '123.456' 5 point = str.find('.') 6 def str2int(a): 7 if a != '.': 8 return int(a) 9 10 def int2float(x,y): 11 return x*10 + y 12 13 result = reduce(int2float,list(map(str2int,str))[:point]) + reduce(int2float,list(map(str2int,str))[point+1:]) * 10**(-(len(str)-point-1)) 14 print(result)
運行結果:函數
[root@HK Practice]# python map_reduce_3.py 123.456 [root@HK Practice]#
代碼分析:字符串
2 3 from functools import reduce #導入reduce模塊 4 str = '123.456' #將須要轉換的字符串賦值 5 point = str.find('.') #用str.find找出小數點的位置 6 def str2int(a): #定義函數,將字符串轉換成int類型 7 if a != '.': 8 return int(a) 9 10 def int2float(x,y): #定義一個求積的函數 11 return x*10 + y 12 13 result = reduce(int2float,list(map(str2int,str))[:point]) + reduce(int2float,list(map(str2int,str))[point+1:]) * 10**(-(len(str)-point-1)) 14 print(result) #前半部分是小數點以前的結果,+以後的部分是小數點以後的部分,10**(-(len(str)-point-1))是經過point肯定新數字小數點的位置