利用map
和reduce
編寫乙個str2float
函式,把字串'123.456'
轉換成浮點數123.456
。
思路:計算小數字數--->將字串中的小數點去掉--->字串轉換為整數--->整數轉換為浮點數
1from functools import
reduce
2def
str2float(s):
3 digits =
4 b=0#
計算小數字數
5 i=0
6while i7if s[i]=='.'
:8 b=len(s)-i-1
9 i=i+1
1011 s=s[:(len(s)-b-1)]+s[(len(s)-b):]12#
字元轉換為整數
13def
f1(s):
14return
digits[s]15#
exp:1,2轉換為12
16def
f2(a,b):
17return a*10+b
18def f3(s):#
整數轉換為浮點數
19for i in
range(b):
20 s=s*0.1
21returns22
return
(f3(reduce(f2,map(f1,s))))
23print(str2float('
12.3456
'))
知識點:
1、將字串中的小數點去掉可以用切片的方法。
2、reduce
把乙個函式作用在乙個序列[x1, x2, x3, ...]
上,這個函式必須接收兩個引數,reduce
把結果繼續和序列的下乙個元素做累積計算,其效果就是:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
將字串轉化為整型
函式名稱 atol 函式原型 long atol cha r str 函式功能 將字串轉換成乙個長整數 函式返回 轉換後的數值 引數說明 str 待轉換為長整型的字串 所屬檔案 include include int ma in 把字串轉換成整數 收藏 題目 輸入乙個表示整數的字串 把該字串轉換成整...
將數字轉化為字串
將數字轉化為字串 方法一 include int main void temp 0 scanf d num number num do while number 0 string i 0 printf number d,位數是 d位 n num,i 統計出位數 for j 0,i j i 2 j i...
Python將字串轉為字典最佳實踐
在工作中我們經常會遇到資料型別之間的互轉的問題,而通常我們請求一些api藉口返回的結果就是字串,但是格式是json的,在python中轉為字典是最易處理的,所以這裡記錄一下在python下把字串轉為字典的三種方法。source code usr bin env python3 author nock...