函数式编程
高阶函数
传入函数
既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数称为高阶函数
def add(x, y, f): return f(x) + f(y) print(add(-3,5,abs))
map/reduce
map(func, *iterables) --> map object
Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.
map()接收两个参数,一个是函数,一个是Iterbale,map将传入的函数依次作用于序列的每个元素,并把结果作为新的Iterator返回
def f(x): return x * x r = map(f, [1,2,3,4,5]) list(r)
把list所有数字转为字符串
list(map(str, [1,2,3,4,5]))
reduce
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,from left to right, so as to reduce the sequence to a single value.For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
reduce()接收两个参数,函数和序列,其中函数也要有两个参数,reduce把结果和序列剩下的部分依次进行计算,效果就是
reduce(f,[x1,x2,x3,x4,x5])=f(f(f(f(x1,x2),x3),x4),x5)
如求和
from functools import reduce def add(x,y): return x+y reduce(add,[1,2,3,4,5])
把序列变换成整数
from functools import reduce def fn(x,y): return x * 10 + y reduce(fn,[1,2,3,4,5])
把str转换成int
from functools import reduce def fn(x,y): return x * 10 + y def chr2num(s): digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} return digits[s] reduce(fn, map(chr2num,'12345'))
整理成str2int的函数
from functools import reduce DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def str2int(s): def fn(x, y): return x * 10 + y def chr2num(s): return DIGITS[s] return reduce(fn, map(chr2num, s))
用lambda函数精简
from functools import reduce DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def chr2num(s): return DIGITS[s] def str2int(s): return reduce(lambda x, y: x * 10 + y, map(chr2num, s))