文章目录
一、什么是高阶函数
可以把函数作为另一个函数的返回值或者参数的函数,成为高阶函数
二、map/reduce
map
def f():
map(f,[]) // 用法和js基本一致,对于列表中的每一个元素作为f的参数,f的返回值作为新列表的子元素返回
def m(x,y): // 必须是两个参数
from functools import reduce // 模块导入
reduce(m,[])// 将列表中的元素作为参数传入m中,最终的计算结果,作为返回值
作业1:字符串转数字
#!/usr/bin/env python3
#encoding=utf-8
from functools import reduce
def str2int(str="12312"):
def formatStr(str):
return int(str)
def toint(x,y):
return x*10+y
return reduce(toint,map(formatStr,str))
作业2:单词首字母转大写
#!/usr/bin/env python3
#encoding=utf-8
from functools import reduce
def strUpper(list):
def toUpper(list):
return list[0].upper()+list[1:].lower()
return map(toUpper,list)
作业三:编写一个prod()函数,可以接受一个list并利用reduce()求积
#!/usr/bin/env python3
#encoding=utf-8
from functools import reduce
def prod(list):
def formatStr(str):
return int(str)
def toprod(x,y):
return x*y
return reduce(toprod,map(formatStr,list))
作业四:利用map和reduce编写一个str2float函数,把字符串’123.456’转换成浮点数123.456
#!/usr/bin/env python3
#encoding=utf-8
from functools import reduce
status = False
num = 0
def str2float(Str):
def formatStr(str):
global status
global num
if str == '.':
status=True
return str
else:
if status:
num = num+1
return int(str)
def sum(x,y):
if y == '.':
return x
else:
return x*10+y
total =reduce(sum,map(formatStr,Str))
for item in range(num):
total = total/10
n = 0
status = False
return total