原文: https://thepythonguru.com/python-builtin-functions/filter/


    于 2020 年 1 月 7 日更新


    filter()函数将一个函数和一个序列作为参数并返回一个可迭代的对象,仅按顺序产生要为其返回True的项目。 如果传递了None而不是函数,则将求值为False的序列中的所有项目删除。 filter()的语法如下:

    语法filter(function or None, iterable) --> filter object

    这是一个例子:

    Python 3

    1. >>>
    2. >>> def is_even(x):
    3. ... if x % 2 == 0:
    4. ... return True
    5. ... else:
    6. ... return False
    7. ...
    8. >>>
    9. >>> f = filter(is_even, [1, 3, 10, 45, 6, 50])
    10. >>>
    11. >>> f
    12. <filter object at 0x7fcd88d54eb8>
    13. >>>
    14. >>>
    15. >>> for i in f:
    16. ... print(i)
    17. ...
    18. 10
    19. 6
    20. 50
    21. >>>

    试试看:

    1. def is_even(x):
    2. if x % 2 == 0:
    3. return True
    4. else:
    5. return False
    6. f = filter(is_even, [1, 3, 10, 45, 6, 50])
    7. print(f)
    8. for i in f:
    9. print(i)

    要立即产生结果,我们可以使用list()函数。

    Python 3

    1. >>>
    2. >>> list(filter(is_even, [1, 3, 10, 45, 6, 50]))
    3. [10, 6, 50]
    4. >>>
    5. >>>
    6. >>> list(filter(None, [1, 45, "", 6, 50, 0, {}, False])) # function argument is None
    7. [1, 45, 6, 50]
    8. >>>

    试一试:

    1. def is_even(x):
    2. if x % 2 == 0:
    3. return True
    4. else:
    5. return False
    6. print( list(filter(is_even, [1, 3, 10, 45, 6, 50])) )
    7. # function argument is None
    8. print( list(filter(None, [1, 45, "", 6, 50, 0, {}, False])) )

    在 Python 2 中,filter()返回实际列表(这不是处理大数据的有效方法),因此您无需将filter()包装在list()调用中。

    Python 2

    1. >>>
    2. >>> filter(is_even, [1, 3, 10, 45, 6, 50])
    3. [10, 6, 50]
    4. >>>

    这是其他一些例子。

    Python 3

    1. >>>
    2. >>> filter(lambda x: x % 2 != 0, [1, 3, 10, 45, 6, 50]) # lambda is used in place of a function
    3. [1, 3, 45]
    4. >>>
    5. >>>
    6. >>> list(filter(bool, [10, "", "py"]))
    7. [10, 'py']
    8. >>>
    9. >>>
    10. >>> import os
    11. >>>
    12. >>> # display all files in the current directory (except the hidden ones)
    13. >>> list(filter(lambda x: x.startswith(".") != True, os.listdir(".") ))
    14. ['Documents', 'Downloads', 'Desktop', 'Pictures', 'bin', 'opt', 'Templates', 'Public', 'Videos', 'Music']
    15. >>>

    试一试:

    1. # lambda is used in place of a function
    2. print(filter(lambda x: x % 2 != 0, [1, 3, 10, 45, 6, 50]))
    3. print(list(filter(bool, [10, "", "py"])))
    4. import os
    5. # display all files in the current directory (except the hidden ones)
    6. print(list(filter(lambda x: x.startswith(".") != True, os.listdir(".") )) )