函数式编程

函数式编程就是对一个序列应用一些函数的工具。

在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]
>>> 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值