码迷,mamicode.com
首页 > 编程语言 > 详细

python内置函数5-filter()

时间:2017-02-22 15:33:43      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:function   sequence   elements   either   returns   

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()

标签:function   sequence   elements   either   returns   

原文地址:http://hdlptz.blog.51cto.com/12553181/1900107

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!