Python内建了map()和reduce()函数。
我们先看map。
map()
函数接收两个参数,一个是函数,一个是
Iterable
,
map
将传入的函数依次作用到序列的每个元素,并把结果作为新的
Iterator
返回。
举例说明,比如我们有一个函数f(x)=x2,要把这个函数作用在一个list [1, 2, 3, 4, 5, 6, 7, 8, 9]
上,就可以用map()
实现如下:
现在,我们用Python代码实现:
>>> 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用法
再看reduce
的用法。reduce
把一个函数作用在一个序列[x1, x2, x3, ...]
上,这个函数必须接收两个参数,reduce
把结果继续和序列的下一个元素做累积计算,其效果就是:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
利用
map
和
reduce
编写一个
str2float
函数,把字符串
'123.456'
转换成浮点数
123.456
:
例子:
# -*- coding: utf-8 -*-
from functools import reduce
def str2float(s):
from functools import reduce
def str2float(s):
print('str2float(\'123.456\') =', str2float('123.456'))
相应代码如下:
from functools import reduce
def str2float(s):
sp =s.split('.')
string = sp[0]+sp[1]
def fun(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
def f(x,y):
return x*10+y
return reduce(f,map(fun,string))
便可以得到浮点数了。重点在于map()函数与reduce()函数连用