Python中的map、reduce和filter浅析

2019-10-06 17:22:21于丽

这个已经介绍的很明了,
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
相当于计算

((((1+2)+3)+4)+5)
而:

reduce(lambda x, y: x+y, [1, 2, 3, 4, 5],6)
相当于计算

(((((6+1)+2)+3)+4)+5)


4、filter

在http://docs.python.org/2/library/functions.html#filter中如下介绍filter函数:

filter(function, iterable)
Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.
参数function(是函数)用于处理iterable中的每个元素,如果function处理某元素时候返回true,那么该元素将作为list的成员而返回。比如,过滤掉字符串中的字符a:

def func(x):
    ''' '''
    return x != 'a'

print filter(func, 'awake')
运行结果是:

wke
这也可以通过列表推导来实现:

print ''.join([x for x in 'awake' if x != 'a'])