如何在Python中使用过滤器函数
发布时间:2023-06-21 21:15:54
在Python中,有一个内置函数叫做filter(),用于筛选序列中符合特定条件的元素并返回一个新的序列。它的语法结构为:
filter(function, iterable)
其中,function是一个自定义函数,用于判断可迭代对象iterable中的每个元素是否符合条件,返回值为True或False;iterable是我们需要过滤的可迭代对象,可以是列表、元组、集合等。
下面我们通过实例来了解如何在Python中使用过滤器函数:
案例1:过滤偶数
我们有一个数字列表,需要过滤出其中的偶数。我们定义一个自定义函数is_even()用于判断非负整数是否为偶数:
def is_even(num):
if num % 2 == 0:
return True
else:
return False
然后我们使用filter()函数来对数字列表进行过滤:
num_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_lst = list(filter(is_even, num_lst)) print(even_lst)
运行结果为:
[2, 4, 6, 8, 10]
案例2:过滤长度大于等于5的字符串
我们有一个字符串列表,需要过滤出其中长度大于等于5的字符串。我们定义一个自定义函数long_str()用于判断字符串的长度是否大于等于5:
def long_str(s):
if len(s) >= 5:
return True
else:
return False
然后我们使用filter()函数来对字符串列表进行过滤:
str_lst = ['apple', 'banana', 'orange', 'grape', 'peach'] long_lst = list(filter(long_str, str_lst)) print(long_lst)
运行结果为:
['apple', 'banana', 'orange', 'grape']
案例3:过滤集合中的负数
我们有一个集合,需要过滤出其中的非负整数。我们可以直接使用lambda表达式来定义判断条件:
num_set = {1, -2, 3, -4, 5, -6, 7, -8, 9, -10}
pos_set = set(filter(lambda x: x >= 0, num_set))
print(pos_set)
运行结果为:
{1, 3, 5, 7, 9}
结语
filter()函数是非常实用的内置函数,它可以帮助我们快速地对列表、元组、集合等方式进行过滤操作,让我们的程序更加高效和简洁。
