有很多文章介紹python的map與reduce,這究竟是什麼樣的東西呢?python
先看看google的paper裏對mapreduce的解釋ide
http://static.googleusercontent.com/media/research.google.com/zh-CN//archive/mapreduce-osdi04.pdf 函數
MapReduce is a programming model and an associated implementation for processing and generating large data sets. Users specify a map function that processes a key/value pair to generate a set of intermediate key/value pairs, and a reduce function that merges all intermediate values associated with the same intermediate key.oop
mapgoogle
map(function, iterable, ...)的第一個參數是一個函數,第二個參數接受一個iterable對象(字符串,列表,元組等)。該函數返回一個列表。spa
python實現map的代碼orm
實現:將輸入的不規範的用戶名轉換成首字母大寫的標準格式對象
邏輯寫的簡單點,就3種狀況,固然能夠寫成4種,就相對複雜了。。。
ip
初次循環,首字母小寫ci
非初次循環,字母大寫
其它(由於初次循環,首字母大寫和非初次循環,字母小寫默認就知足咱們的需求)
def lower2upper(s): loop = 0 '''循環計數''' str = "" '''定義一個空字符串''' for i in s: if i.islower() and loop ==0: str = str + i.upper() loop +=1 elif i.isupper() and loop !=0: str = str + i.lower() loop +=1 else: str = str + i loop +=1 return str result = map(lower2upper,["adam","LiSA","ChEn","Peter","tOM"]) print result
reduce
reduce(function, iterable[, initializer])把函數從左到右累積做用在元素上,產生一個數值。如reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])就是計算((((1+2)+3)+4)+5)。Python提供的sum()函數能夠接受一個list並求和,現實現一個prod()函數,能夠接受一個list並利用reduce()求積。
def prod(list):
def multiply(x, y):
return x * y
return reduce(multiply, list)
print prod([1, 3, 5, 7])
map和reduce
咱們能夠綜合利用map和reduce來完成一個簡單的字符串到數字的程序。
def str2int(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}
return reduce(fn, map(char2num, s))
print str2int("12345")
其中map用於將字符串拆分爲對應的數字,並以list的方式返回。reduce用來累加各個位上的和。