Python:利用map和reduce編寫一個str2float函式,把字串'123.456'轉換成浮點數123.456
阿新 • • 發佈:2019-02-17
# -*- coding: utf-8 -*- from functools import reduce def str2float(s): def fn(x, y): return x * 10 + y 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] # 得到字串中.的索引 n = s.index('.') # 根據.的位置將字串切片為兩段 s1 = list(map(int, [x for x in s[: n]])) s2 = list(map(int, [x for x in s[n + 1 :]])) # m ** n表示m的n次方 return reduce(fn, s1) + reduce(fn, s2) / 10 ** len(s2) # 測試結果是否正確 print('str2float(\'123.456\')=',str2float('123.456'))
答案非原創,只是對別人的答案進行了完善和總結。
總結:
map()
函式接收兩個引數,一個是函式,一個是Iterable
,map
將傳入的函式依次作用到序列的每個元素,並把結果作為新的Iterator
返回。比如map(int, ['1', '2', '3']) 就是把字元1、2、3都轉換為int型別。
reduce
把一個函式作用在一個序列[x1, x2, x3, ...]
上,這個函式必須接收兩個引數,reduce
把結果繼續和序列的下一個元素做累積計算,就像這樣:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)