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
.
相反,f
in 返回的值filter(f, ...)
不是其中的项result
.f(i)
仅用于确定是否i
应保留该值result
.
在Python2,map
并filter
返回列表.在Python3,map
并filter
返回迭代器.以上,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)
归档时间: |
|
查看次数: |
15741 次 |
最近记录: |