map/reduce
map:实现函数和Iterable
的结合
举例:求平方
>>> 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]
reduce:一次接受两个参数,并累计计算。
举例:求和
>>> from functools import reduce
>>> def add(x, y):
... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
练习
- 利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:
['adam', 'LISA', 'barT']
,输出:['Adam', 'Lisa', 'Bart']
:
def normalize(name):
return name.lower().title()
pass
# 测试:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
- Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用
reduce()
求积:
from functools import reduce
def prod(L):
def fn(x,y):
return x * y
return reduce(fn,L)
pass
# 测试
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
print('测试成功!')
else:
print('测试失败!')
- 利用
map
和reduce
编写一个str2float
函数,把字符串'123.456'
转换成浮点数123.456
:
# -*- coding: utf-8 -*-
from functools import reduce
def str2float(s):
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]
s2 = ''.join(s.split('.')) # 剔除‘.’
r = reduce(lambda x ,y : x*10 + y ,map(char2num,s2))
return r / 10 ** len(s.split('.')[-1]) # 将int转为float
# 测试
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('测试成功!')
else:
print('测试失败!')
这里还有一种处理办法,可以替换掉s2
和lambda
的步骤,让reduce
直接调用fn
def fn(x,y):
if y == None:
return x
else:
return x*10 + y