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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值