python内置函数5-filter()

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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‘]


本文出自 “大云技术” 博客,请务必保留此出处http://hdlptz.blog.51cto.com/12553181/1900107

以上是关于python内置函数5-filter()的主要内容,如果未能解决你的问题,请参考以下文章

python有多少内置函数

python如何查看内置函数

Python 内置函数

python基础9 -----python内置函数

Python isinstance() 函数 Python 内置函数 Python 内置函数

python 函数--内置函数