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

Python内置函数之filter函数的用法及实例

发布时间:2023-05-28 13:48:32

Python内置函数之filter函数的用法及实例

filter()函数是Python内置的用于对指定序列进行筛选的函数,一般用于对可迭代对象进行过滤,其返回值是一个可迭代对象,其中包含了序列中满足条件的元素。

filter()函数的语法如下:

filter(function, iterable)

其中,function是一个函数,用于对可迭代对象进行过滤;iterable是一个可迭代对象,表示需要过滤的序列。

filter()函数返回的是一个可迭代对象,其中包含了序列中满足条件的元素。

下面,我们来看一些filter()函数的使用实例。

实例一:过滤奇数

我们需要从一个列表中过滤出所有的奇数,可以使用filter()函数来实现:

def is_odd(n):
    return n % 2 == 1

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = filter(is_odd, lst)

print(list(result))

运行结果为:

[1, 3, 5, 7, 9]

在这个例子中,我们定义了一个函数is_odd(n),用于判断n是否为奇数,返回值为True或者False。然后,我们使用filter()函数和上述函数对列表lst进行过滤,得到结果为[1, 3, 5, 7, 9]。

实例二:过滤出长度大于等于4的字符串

我们需要从一个列表中过滤出所有长度大于等于4的字符串,可以使用filter()函数和lambda表达式来实现:

lst = ['hello', 'world', 'python', 'programming']
result = filter(lambda s: len(s) >= 4, lst)

print(list(result))

运行结果为:

['hello', 'world', 'python', 'programming']

在这个例子中,我们使用lambda表达式来表示判断字符串长度是否大于等于4,对列表lst进行过滤,得到结果为['hello', 'world', 'python', 'programming']。

实例三:过滤出包含数字的字符串

我们需要从一个列表中过滤出所有包含数字的字符串,可以使用filter()函数和re模块来实现:

import re

lst = ['hello123', 'world', '3python', 'programming']
result = filter(lambda s: bool(re.search('\d', s)), lst)

print(list(result))

运行结果为:

['hello123', '3python']

在这个例子中,我们使用lambda表达式来表示判断字符串中是否包含数字,使用re.search()函数进行正则匹配。对列表lst进行过滤,得到结果为['hello123', '3python']。

综上,filter()函数是Python内置的一个非常有用的函数,能够帮助我们对可迭代对象进行过滤,获取符合条件的元素。在实际编程中,我们会经常用到这个函数,希望本文能对大家有所帮助。