map、filter 和 reduce
这三个函数号称是函数式编程的代表。在 Python3.x 和 Python2.x 中也有了很大的差异。
首先我们先简单的在 Python2.x 的交互下输入 map 和 filter,看到它们两者的类型是 built-in function(内置函数):
>>> map
<built-infunction map>
>>> filter
<built-infunction filter>
>>>
它们输出的结果类型都是列表:
>>> map(lambda x:x *2,[1,2,3])
[2,4,6]
>>> filter(lambda x:x %2==0,range(10))
[0,2,4,6,8]
>>>
但是在Python 3.x中它们却不是这个样子了:
>>> map
<class'map'>
>>> map(print,[1,2,3])
<map object at 0x10d8bd400>
>>> filter
<class'filter'>
>>> filter(lambda x:x %2==0, range(10))
<filter object at 0x10d8bd3c8>
>>>
首先它们从函数变成了类,其次,它们的返回结果也从当初的列表成了一个可迭代的对象, 我们尝试用 next 函数来进行手工迭代:
>>> f =filter(lambda x:x %2==0, range(10))
>>>next(f)
0
>>>next(f)
2
>>>next(f)
4
>>>next(f)
6
>>>
对于比较高端的 reduce 函数,它在 Python 3.x 中已经不属于 built-in 了,被挪到 functools 模块当中。