函数式编程就是对一个序列应用一些函数的工具。
在python中,filter、reduce、map都是函数式编程的工具。
其中,学习一下reduce。
reduce接受一个函数和一组数据作为参数,每次给使用之前函数的返回值并且再给函数传递一个数据作为参数。
例如:
上面的reduce每次把a中的一个数据加到之前的函数返回值中。最后得到总和。
------------------------------------------------
下面是使用map和filter的例子。可以参考。
>>> help(map)
Help on built-in function map in module __builtin__:
map(...)
map(function, sequence[, sequence, ...]) -> list
Return a list of the results of applying the function to the items of
the argument sequence(s). If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length. If the function is None, return a list of
the items of the sequence (or a list of tuples if more than one sequence).
>>> def pp(a):
print a
return a**a
>>> map(pp,a)
1
2
3
4
[1, 4, 27, 256]
>>> help(filter)
Help on built-in function filter in module __builtin__:
filter(...)
filter(function or None, sequence) -> list, tuple, or string
Return those items of sequence for which function(item) is true. If
function is None, return the items that are true. If sequence is a tuple
or string, return the same type, else return a list.
>>> def fil(a):
if a%2==0:
return True
return False
>>> filter(fil,a)
[2, 4]
>>>