企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# Python `filter()`函数 > 原文: [https://thepythonguru.com/python-builtin-functions/filter/](https://thepythonguru.com/python-builtin-functions/filter/) * * * 于 2020 年 1 月 7 日更新 * * * `filter()`函数将一个函数和一个序列作为参数并返回一个可迭代的对象,仅按顺序产生要为其返回`True`的项目。 如果传递了`None`而不是函数,则将求值为`False`的序列中的所有项目删除。 `filter()`的语法如下: **语法**: `filter(function or None, iterable) --> filter object` 这是一个例子: **Python 3** ```py >>> >>> def is_even(x): ... if x % 2 == 0: ... return True ... else: ... return False ... >>> >>> f = filter(is_even, [1, 3, 10, 45, 6, 50]) >>> >>> f <filter object at 0x7fcd88d54eb8> >>> >>> >>> for i in f: ... print(i) ... 10 6 50 >>> ``` 试试看: ```py def is_even(x): if x % 2 == 0: return True else: return False f = filter(is_even, [1, 3, 10, 45, 6, 50]) print(f) for i in f: print(i) ``` 要立即产生结果,我们可以使用`list()`函数。 **Python 3** ```py >>> >>> list(filter(is_even, [1, 3, 10, 45, 6, 50])) [10, 6, 50] >>> >>> >>> list(filter(None, [1, 45, "", 6, 50, 0, {}, False])) # function argument is None [1, 45, 6, 50] >>> ``` 试一试: ```py def is_even(x): if x % 2 == 0: return True else: return False print( list(filter(is_even, [1, 3, 10, 45, 6, 50])) ) # function argument is None print( list(filter(None, [1, 45, "", 6, 50, 0, {}, False])) ) ``` 在 Python 2 中,`filter()`返回实际列表(这不是处理大数据的有效方法),因此您无需将`filter()`包装在`list()`调用中。 **Python 2** ```py >>> >>> filter(is_even, [1, 3, 10, 45, 6, 50]) [10, 6, 50] >>> ``` 这是其他一些例子。 **Python 3** ```py >>> >>> filter(lambda x: x % 2 != 0, [1, 3, 10, 45, 6, 50]) # lambda is used in place of a function [1, 3, 45] >>> >>> >>> list(filter(bool, [10, "", "py"])) [10, 'py'] >>> >>> >>> import os >>> >>> # display all files in the current directory (except the hidden ones) >>> list(filter(lambda x: x.startswith(".") != True, os.listdir(".") )) ['Documents', 'Downloads', 'Desktop', 'Pictures', 'bin', 'opt', 'Templates', 'Public', 'Videos', 'Music'] >>> ``` 试一试: ```py # lambda is used in place of a function print(filter(lambda x: x % 2 != 0, [1, 3, 10, 45, 6, 50])) print(list(filter(bool, [10, "", "py"]))) import os # display all files in the current directory (except the hidden ones) print(list(filter(lambda x: x.startswith(".") != True, os.listdir(".") )) ) ``` * * * * * *