python函数式编程
1.高阶函数 将函数作为参数传入 1)map/reduce map:传入两个参数,一个是函数,一个是迭代器,主要作用是将运算规则抽象化表达,如: >>> def f(x): return x * x >>> r = map(f,[1,2,3,4,5,6,7]) >>> list(r) [1, 4, 9, 16, 25, 36, 49] reduce:传入两个参数,做累计效果 将[1,3,5,6]变成1356 >>> from functools import reduce >>> def fn(x,y): return x*10 + y >>> reduce(fn,[1,3,5,6]) 1356 也可将str转换成int 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 char2num(s): return DIGITS[s] return reduce(fn, map(char2num, s)) 2)fliter:用于过滤序列 def is_odd(n): return n % 2 == 1