高阶函数: 一个函数可以接收另一个函数名作为参数
1.变量可以指向函数
2.函数名也是变量
一、map/reduce
练习
利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:
# -*- coding: utf-8 -*-
def normalize(name):
name = name[0].upper()+name[1:].lower()
return name
# 测试:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
练习
Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积:
# -*- coding: utf-8 -*-
from functools import reduce
def prod(L):
def multi(a,b):
return a*b
return reduce(multi,L)
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 str2num(s):
return DIGITS[s]
def num2float(x,y):
return x*10+y
number = reduce(num2float,map(str2num,s.replace('.','')))
point = s.find('.')
return number/pow(10,len(s)-1-point)
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('测试成功!')
else:
print('测试失败!')

831

被折叠的 条评论
为什么被折叠?



