简体   繁体   English

是否可以仅使用地图来实现过滤器功能?

[英]Is it possible to implement filter function using only map?

I was wondering whether it is possible to implement filter function using only map function in Python. 我想知道是否有可能仅在Python中使用map函数来实现filter功能。 Suppose I have a list A = [1,2,3,4,5,6,7,8,9,10] and I want to get only even numbers. 假设我有一个列表A = [1,2,3,4,5,6,7,8,9,10]而我只想得到偶数。 Applying filter function provides me a list of 5 elements but map always returns 10 elements no matter what functions I could think. 应用filter功能为我提供了5个元素的列表,但是无论我想到什么功能, map始终返回10个元素。

Is there any way to achieve this? 有什么办法可以做到这一点?

Please don't suggest to apply filter again on the result of map . 请不要建议对map的结果再次应用filter :-) :-)

No. map will only apply a function to all the elements of the list. 编号map只会将功能应用于列表的所有元素。 Thus, the number of elements in the resulting list (or generator) will always be the same as in the original list. 因此,结果列表(或生成器)中元素的数量将始终与原始列表中的元素数量相同。

(Technically, you could use map with a function that uses side-effects to add the even elements to some other list and use that list as the result, but this is not how map is supposed to be used.) (从技术上讲,您可以map与带有副作用的函数一起使用,以将偶数元素添加到其他列表中,并将该列表用作结果,但这不是应该使用map方式。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM