Python:过滤器(函数,序列)和映射(函数,序列)之间的区别 [英] Python: Difference between filter(function, sequence) and map(function, sequence)

查看:258
本文介绍了Python:过滤器(函数,序列)和映射(函数,序列)之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过Python文档阅读,深入了解Python语言,并遇到了过滤和映射函数。我之前使用过滤器,但从未映射过,尽管我已经在SO上看到过各种Python问题。

在Python教程中阅读完这些内容后,我对两者之间的区别感到困惑。例如,从 5.1.3。函数式编程工具

 >>> def f(x):return x%2!= 0 and x%3!= 0 
...
>>>过滤器(f,范围(2,25))
[5,7,11,13,17,19,23]



 >>> def cube(x):return x * x * x 
...
>>>地图(立方体,范围(1,11))
[1,8,27,64,125,216,343,512,729,1000]

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

为什么 map 有时会返回一个布尔值,而其他时间会返回实际返回值?

有人可以向我解释 map 过滤器

解决方案

  map(cube,range(1,11))

相当于

  [cube(1),cube(2),...,cube(10)] 


 过滤器(f,范围(2,25))
返回的列表

相当于 result 运行后

  result = [] 
在范围内(2,25):
如果f(i):
结果。 append(i)

请注意,当使用 map 中,结果中的项目是由函数 cube 返回的值。



相比之下, 过滤器(f,...)不是结果中的项目 code>。 f(i)仅用于确定是否值 i 应保存在结果


I'm reading through the Python documentation to really get in depth with the Python language and came across the filter and map functions. I have used filter before, but never map, although I have seen both in various Python questions here on SO.

After reading about them in the Python tutorial, I'm confused on the difference between the two. For example, from 5.1.3. Functional Programming Tools:

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

and

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

These looked almost exactly the same in function to me, so I went into terminal to run Python interactively and tested out my own case. I used map for both the first and second instances above, and for the first one ( return x % 2 != 0 and x % 3 != 0 ) it returned a list of booleans rather than numbers.

Why does map sometimes return a boolean and other times the actual return value?

Can someone explain to me exactly the difference between map and filter?

解决方案

map(cube, range(1, 11))

is equivalent to

[cube(1), cube(2), ..., cube(10)]

While the list returned by

filter(f, range(2, 25))

is equivalent to result after running

result = []
for i in range(2, 25):
    if f(i):
        result.append(i)

Notice that when using map, the items in the result are values returned by the function cube.

In contrast, the values returned by f in filter(f, ...) are not the items in result. f(i) is only used to determine if the value i should be kept in result.

这篇关于Python:过滤器(函数,序列)和映射(函数,序列)之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆