原文: https://thepythonguru.com/python-builtin-functions/filter/
于 2020 年 1 月 7 日更新
filter()函数将一个函数和一个序列作为参数并返回一个可迭代的对象,仅按顺序产生要为其返回True的项目。 如果传递了None而不是函数,则将求值为False的序列中的所有项目删除。 filter()的语法如下:
语法: filter(function or None, iterable) --> filter object
这是一个例子:
Python 3
>>>>>> 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)...10650>>>
试试看:
def is_even(x):if x % 2 == 0:return Trueelse:return Falsef = filter(is_even, [1, 3, 10, 45, 6, 50])print(f)for i in f:print(i)
要立即产生结果,我们可以使用list()函数。
Python 3
>>>>>> 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]>>>
试一试:
def is_even(x):if x % 2 == 0:return Trueelse:return Falseprint( list(filter(is_even, [1, 3, 10, 45, 6, 50])) )# function argument is Noneprint( list(filter(None, [1, 45, "", 6, 50, 0, {}, False])) )
在 Python 2 中,filter()返回实际列表(这不是处理大数据的有效方法),因此您无需将filter()包装在list()调用中。
Python 2
>>>>>> filter(is_even, [1, 3, 10, 45, 6, 50])[10, 6, 50]>>>
这是其他一些例子。
Python 3
>>>>>> 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']>>>
试一试:
# lambda is used in place of a functionprint(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(".") )) )
