Python:过滤器(函数,序列)和映射(函数,序列)之间的区别

sam*_*rap 29 python functional-programming filterfunction map-function

我正在阅读Python文档,以深入了解Python语言并遇到过滤器和地图功能.我之前使用过滤器,但从未映射过,虽然我已经在SO上看到了各种Python问题.

在Python教程中阅读了它们之后,我对两者之间的区别感到困惑.例如,从5.1.3开始.功能编程工具:

>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
Run Code Online (Sandbox Code Playgroud)

>>> def cube(x): return x*x*x
...
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Run Code Online (Sandbox Code Playgroud)

这些看起来与我的功能几乎完全相同,所以我进入终端以交互方式运行Python并测试了我自己的情况.我用于map上面的第一个和第二个实例,并且对于第一个实例(return x % 2 != 0 and x % 3 != 0)它返回了一个布尔值而不是数字列表.

为什么map有时会返回布尔值,有时会返回实际返回值?

有人可以向我解释一下map和之间的区别filter吗?

unu*_*tbu 35

list(map(cube, range(1, 11)))
Run Code Online (Sandbox Code Playgroud)

相当于

[cube(1), cube(2), ..., cube(10)]
Run Code Online (Sandbox Code Playgroud)

而列表返回

list(filter(f, range(2, 25)))
Run Code Online (Sandbox Code Playgroud)

相当于跑完result之后

result = []
for i in range(2, 25):
    if f(i):
        result.append(i)
Run Code Online (Sandbox Code Playgroud)

请注意,使用时map,结果中的项是函数返回的值cube.

相反,fin 返回的值filter(f, ...)不是其中的项result.f(i)仅用于确定是否i应保留该值result.


在Python2,mapfilter返回列表.在Python3,mapfilter返回迭代器.以上,list(map(...))list(filter(...))用于确保结果是一个列表.


CT *_*Zhu 23

filter()顾名思义,过滤原始的iterable,并重新为返回True的函数提供filter().

map() 另一方面,将提供的函数应用于iterable的每个元素,并返回每个元素的结果列表.

按照你给出的例子,让我们比较它们:

>>> def f(x): return x % 2 != 0 and x % 3 != 0
>>> range(11)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> map(f, range(11))  # the ones that returns TRUE are 1, 5 and 7
[False, True, False, False, False, True, False, True, False, False, False]
>>> filter(f, range(11))  # So, filter returns 1, 5 and 7
[1, 5, 7]
Run Code Online (Sandbox Code Playgroud)