Python内置函数_filter函数

1. 概念

1.1 描述

filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换(注:py2.X直接返回一个列表)。

​ 该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

1.2 语法

filter(function, iterable)

参数说明

  • function:判断函数
  • iterable:可迭代对象

源码内容

class filter(object):
    """
    filter(function or None, iterable) --> filter object
    
    Return an iterator yielding those items of iterable for which function(item)
    is true. If function is None, return the items that are true.
    """
    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __init__(self, function_or_None, iterable): # real signature unknown; restored from __doc__
        pass

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __next__(self, *args, **kwargs): # real signature unknown
        """ Implement next(self). """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        """ Return state information for pickling. """
        pass

1.3 返回值

  • Py2.X 返回列表
  • Py3.X 返回可迭代对象

2. 实例

# 1.筛选出列表中的奇数
def is_odd(x):
    return x%2 == 1

odd_list_obj = filter(is_odd,[1,2,3,4,5,6,7,8,9])
print(odd_list_obj) #  返回迭代器对象
odd_list = list(odd_list_obj)
print(odd_list) # [1, 3, 5, 7, 9]


# 2.lambda实现筛选列表中的奇数
odd_obj = filter(lambda x:x%2==1,[1,2,3,4,5,6,7,8,9])
print(list(odd_obj))    # [1, 3, 5, 7, 9]



# 3.过滤1-100中的平方根是整数的数值
import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0

tmplist = filter(is_sqr, range(1, 101))
newlist = list(tmplist)
print(newlist)

你可能感兴趣的:(python)