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]
本文介绍了Python内置函数filter的功能,它用于根据指定条件筛选序列元素,并返回一个迭代器。当function为空时,filter相当于去除false值的元素。文中包含filter函数的直译解释和使用示例。
1544

被折叠的 条评论
为什么被折叠?



