首页 › 参考手册 › 内置函数 › filter()

Python filter() 函数

描述

用函数过滤可迭代对象,保留函数返回真值的元素。如果 function 为 None,则保留本身为真的元素。

语法

filter(function, iterable)

参数

参数说明
function判断函数,或 None
iterable可迭代对象

返回值

迭代器

实例

nums = range(1, 11)
print(list(filter(lambda x: x % 3 == 0, nums)))
print(list(filter(None, [0, 1, "", "a", None])))
以上实例输出结果为:
[3, 6, 9]
[1, 'a']