欢迎访问宙启技术站
智能推送

详解Python中的filter()函数及其实例代码

发布时间:2023-06-18 07:17:43

Python中的filter()函数是用于过滤序列中的元素,从而提取出符合条件的所有元素并返回一个新的序列,它的语法结构如下:

filter(function, iterable)

其中,function是一个函数,接收一个参数并返回布尔值;iterable是一个可迭代对象,即可以是列表、元组、字典、集合等。 该方法返回的是一个迭代器,需要用list()等函数转为列表。

通过这个函数我们可以很方便地筛选出符合条件的元素,并且可以处理各种类型的可迭代对象,达到我们快速处理数据的目的。

下面是一些示例代码:

# 过滤出列表中所有的奇数

def is_odd(n):

    return n % 2 == 1

print(list(filter(is_odd, [1, 2, 3, 4, 5, 6])))

# 过滤出列表中所有的偶数

def is_even(n):

    return n % 2 == 0

print(list(filter(is_even, [1, 2, 3, 4, 5, 6])))

# 过滤出列表中所有的负数

def is_negative(n):

    return n < 0

print(list(filter(is_negative, [-1, 2, -3, 4, -5, 6])))

# 删掉空字符串

def not_empty(s):

    return s and s.strip()

print(list(filter(not_empty, ['hello', '', 'world', '', '']))) 

# 过滤出字典中value大于5的键值对

dic = {'a': 1, 'b': 2, 'c': 7, 'd': 9}

print(dict(filter(lambda x: x[1] > 5, dic.items())))

上述示例代码都是基于filter()函数进行数据筛选的,而这个函数本身非常灵活,代码的能够适应各种不同的场景,可以根据自己的需要灵活运用。