11 map和reduce的使用

2022-07-21 02:57:12 字數 1153 閱讀 3900

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

>>> def f(x):

... return x * x

...>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> list(r)

[1, 4, 9, 16, 25, 36, 49, 64, 81]

map()傳入的第乙個引數是f,即函式物件本身。由於結果r是乙個iterator,iterator是惰性序列,因此通過list()函式讓它把整個序列都計算出來並返回乙個list

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
如果考慮到字串str也是乙個序列,對上面的例子稍加改動,配合map(),我們就可以寫出把str轉換為int的函式:

>>> from functools import reduce

>>> def fn(x, y):

... return x * 10 + y

...>>> def char2num(s):

... return [s]

...>>> reduce(fn, map(char2num, '13579'))

13579

from functools import reduce

def str2int(s):

def fn(x, y):

return x * 10 + y

def char2num(s):

return [s]

還可以用lambda函式進一步簡化成:

from functools import reduce

def char2num(s):

return [s]

def str2int(s):

return reduce(lambda x, y: x * 10 + y, map(char2num, s))

C 學習筆記11 map

map簡介 使用map包含map類所在的標頭檔案 include 定義乙個map物件 mapmaptest 容器型別 關聯 key value 實現方式 紅黑樹插入資料 插入資料的四種方式 maptest aaa 100 maptest.insert map value type bbb 200 m...

python中map 和reduce 的使用

map 會根據提供的函式對指定序列做對映。map function,iterable,python 3.x 返回迭代器。print map 返回迭代器位址 一般和list一起用 才能輸出 reduce 函式會對引數序列中元素進行累積。先對集合中的第 1 2 個元素進行操作,得到的結果再與第三個資料用...

map和reduce 個數的設定

一 控制hive任務中的map數 1.通常情況下,作業會通過input的目錄產生乙個或者多個map任務。主要的決定因素有 input的檔案總個數,input的檔案大小,集群設定的檔案塊大小 目前為128m,可在hive中通過set dfs.block.size 命令檢視到,該引數不能自定義修改 2....