Python 内建函数 - filter(function, iterable)

时间:2021-09-16 20:05:07

Manual

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.

See itertools.filterfalse() for the complementary function that returns elements of iterable for which function returns false.

直译

function 可以返回真值的 iterable 的元素构造一个迭代器。iterable可以是序列、支持迭代的容器或是一个迭代器。如果function为空,则假定恒等函数,即移除所有为false值的迭代元素。
注意:如果function函数不为空,且(item for item in iterable if item) 的if函数不为空,那么filter(function, iterable)等价于生成器表达式(item for item in iterable if function(item))。

实例

# 匿名函数lambda
>>> list(filter(lambda x: x % 2 == 0, range(20)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

拓展阅读

lambda
map()