Python之map 和reduce 函式。

2021-08-15 05:54:03 字數 1946 閱讀 1102

python內建map()和reduce()函式

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

map()傳入的第乙個引數是f,即函式物件本身。

比如有乙個函式f(x)=x2,要把這個函式作用在乙個list [1, 2, 3, 4, 5, 6, 7, 8, 9]上,就可以用map()實現如下:

結果:

[1, 4, 9, 16, 25, 36, 49, 64, 81]
把list所有數字轉為字串:

map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])
結果:

['1', '2', '3', '4', '5', '6', '7', '8', '9']
reduce

(f, [x1, x2, x3, x4]) = f

(f(f(x1, x2), x3), x4)

把序列[1, 3, 5, 7, 9]變換成整數13579

def

fn(x, y):

return x * 10 + y

reduce(fn, [1, 3, 5, 7, 9])

結果:

13579
字串str也是乙個序列,reduce()配合map(),把str轉換為int的函式:

def

str2int

(s):

deffn

(x, y):

return x * 10 + y

defchar2num

(s):

return [s]

return reduce(fn, map(char2num, s))

用lambda函式進一步簡化成:

def

char2num

(s):

return [s]

defstr2int

(s):

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

利用map()函式,把使用者輸入的不規範的英文名字,變為首字母大寫,其他小寫的規範名字。輸入:[『adam』, 『lisa』, 『bart』],輸出:[『adam』, 『lisa』, 『bart』]。

def

upperfirstonly

(s):

return s[0].upper()+s[1:].lower()

defop

(s):

return map(upperfirstonly,s)

op(['adam', 'lisa', 'bart'])

結果:

['adam', 'lisa', 'bart']
接收乙個list並利用reduce()求積:

def

prop

(s):

return reduce(lambda x,y:x*y,s)

prod([1,2,3,4,5])

結果:

120

python學習之map函式和lambda函式

map 是 python 內建的高階函式,它接收乙個函式 f 和乙個 list,並通過把函式 f 依次作用在 list 的每個元素上,得到乙個新的 list 並返回。map function,iterable,在map中,不會對itetable進行修改 def fun x return 2 x t ...

Python之Map高階函式

map 函式 map 是 python 內建的高階函式,它接收乙個函式 f 和乙個 list,並通過把函式 f 依次作用在 list 的每個元素上,得到乙個新的 list 並返回。例如,對於list 1,2,3,4,5,6,7,8,9 如果希望把list的每個元素都作平方,就可以用map 函式 因此...

Python資料之map 函式

map 函式的作用 map 函式是 python 內建的高階函式,它接收乙個函式 f 和乙個 list,並通過把函式 f 依次作用在 list 的每個元素上,得到乙個新的 list 並返回。用法 map function,iterable,引數function傳的是乙個函式名,可以是python內建...