map()、filter()和reduce()是python提供的几个常用的函数式编程接口,性能好,直接由C语言写的,运行时不需要通过python解释器间接调用,并且内部做了诸多优化。
map()
map(function, iterable)函数,它表示,对iterable中的每个元素,都运用function这个函数,最后返回一个新的可遍历的集合:
l = [1, 2, 3, 4, 5]
new_list = map(lambda x: x * 2, l) # [2, 4, 6, 8, 10]
python3 -mtimeit -s'xs=range(1000000)' 'map(lambda x: x*2, xs)'
2000000 loops, best of 5: 171 nsec per loop
python3 -mtimeit -s'xs=range(1000000)' '[x * 2 for x in xs]'
5 loops, best of 5: 62.9 msec per loop
python3 -mtimeit -s'xs=range(1000000)' 'l = []' 'for i in xs: l.append(i * 2)'
5 loops, best of 5: 92.7 msec per loop
可以看出,同样的功能,list comprehension和for循环的性能都不如map。
filter()
filter()函数表示对iterable中的每个元素,都使用function判断,并返回True或者False,最后将返回True的元素组成一个新的可遍历的集合。比如我要返回一个列表中的所有偶数,可以写成下面这样:
l = [1, 2, 3, 4, 5]
new_list = filter(lambda x: x % 2 == 0, l) # [2, 4]
reduce()
它通常用来对一个集合做一些累积操作。function同样是一个函数对象,规定它有两个参数,表示对iterable中的每个元素以及上一次调用后的结果,运用function进行计算,所以最后返回的是一个单独的数值。举个例子,我想要计算某个列表元素的乘积,就可以用reduce()函数来表示:
l = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, l) # 1*2*3*4*5 = 120