1. 程式人生 > >Python中的map()和reduce()以及一些栗子

Python中的map()和reduce()以及一些栗子

一.map()函式接收兩個引數,一個是函式,一個是iterable, map將傳入的函式依次作用到序列的每個元素,並把結果作為新的Iterator返回。

二.reduce()把一個函式作用在一個序列上,這個函式必須接收兩個引數, reduce把結果繼續和序列的下一個元素做累積計算

先看map的用法:

栗子1:

def f(x):
return x*x
r = map(f,[1,2,3,4,5,6,7,8,9,10])
print(list(r))
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
map()傳入的第一個引數是f,即函式物件本身。由於結果是一個IteratorIterator
是惰性序列,因此通過list()函式讓它把整個序列都計算出來並返回一個list。

栗子2:

def normalize(name):
    return str(name[0]).upper() + str(name[1:]).lower()

# 測試:
L1 = ['applE', 'liSA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
結果:['Apple', 'Lisa', 'Bart']
(不知道格式怎麼出問題了,所以直接放文字)

再看reduce的用法:

from functools import reduce

def add(x, y
): return x + y print(reduce(add, [1, 3, 5, 7, 9]))
結果25,emmm,這個Python有內建函式sum(),效果是一樣的

再來一個:Python提供的sum()函式可以接受一個list並求和,編寫一個函式,可以接受一個list並利用reduce()求積:

from functools import reduce


def fn(x, y):
return x * y
def prod(L):
return reduce(fn, L)

#使用lambda表示式
def prod(L):
return reduce(lambda x, y: x * 
y, L) print('1 * 2 * 3 * 4 =', prod([1, 2, 3, 4])) if prod([1, 2, 3, 4]) == 24: print('測試成功!') else: print('測試失敗!')
當然是成功的!

綜合的:

利用map和reduce編寫一個str2float函式

說實話,實在想不出來怎麼寫,但是找到了網上的兩種方式,這裡做個記錄, 以後可以回頭看看:方式一:
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]  
   return reduce(fn, map(char2num, s.replace(".","")))  
s="1234.567"  
if s.find(".")!=-1:  
     print('str2float(\'%s\') ='%s, str2float(s)/pow(10,(len(s)-s.find(".")-1)))  
else:  
     print('str2float(\'%s\') ='%s, str2float(s))  
方式二:
from functools import reduce
def str2float(s):
    def fn(x,y):
        return x*10+y
    n=s.index('.')
    s1=list(map(int,[x for x in s[:n]]))
    s2=list(map(int,[x for x in s[n+1:]]))
    return reduce(fn,s1) + reduce(fn,s2)/10**len(s2)
print('\'123.4567\'=',str2float('123.4567'))    

這個是自己結合了一下,覺得比較好理解的一種,也稍微嚴謹了一點
def str2float(s):
def fn(x, y):
return x * 10 + y
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

    def char2num(s):
return DIGITS[s]

    i = s.index(".")
    if i != -1:
if i != 0:
s1 = list(map(char2num, [x for x in s[:i]]))
        else:
s1 = 0
s2 = list(map(char2num, [x for x in s[i + 1:]]))
        return reduce(fn, s1) + reduce(fn, s2) / 10 ** len(s2)


print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('測試成功!')
else:
print('測試失敗!')

這樣,如果直接是個小於一的小數也可以轉換