python內置函數5-filter()

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']


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章