Help on built-in function filter in module __builtin__:


filter(...)

    filter(function or None, sequence) -> list, tuple, or string

    

    Return those items of sequence for which function(item) is true.  If

    function is None, return the items that are true.  If sequence is a tuple

    or string, return the same type, else return a list.


filter(function, iterable)

Construct a list 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 iterable is a string or a tuple, the result also has that type; otherwise it is always a list. 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 [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.ifilter() and itertools.ifilterfalse() for iterator versions of this function, including a variation that filters for elements where the function returns false.


中文说明:

该函数的目的是提取出seq中能使func为true的元素序列。func函数是一个布尔函数,filter()函数调用这个函数一次作用于seq中的每一个元素,筛选出符合条件的元素,并以列表的形式返回。


>>> nums=[2,3,6,12,15,18]

>>> def nums_res(x):

...     return x%2 == 0 and x%3 == 0

... 

>>> print filter(nums_res,nums)

[6, 12, 18]

>>> def is_odd(n):

...     return n%2==1

... 

>>> filter(is_odd, [1,2,4,5,6,9,10,15])

[1, 5, 9, 15]

>>> def not_empty(s):

...     return s and s.strip()

... 

>>> filter(not_empty, ['A','','B',None,'C','  '])

['A', 'B', 'C']