Python中的filter()函数是怎么用的?
Python中的filter()函数是一种内置函数,能够使用给定的函数对列表或序列的每个元素进行过滤,并返回包含满足条件的元素的新列表。
filter()函数的语法如下:
filter(function, iterable)
其中,function是一个处理函数,用来测试可迭代对象(iterable)的每个元素;iterable指定被过滤的列表或序列。
使用filter()函数的一般流程如下:
1. 创建一个迭代器对象。
2. 定义一个返回布尔值的过滤函数,过滤函数会根据给定的条件来选择要保留的元素。
3. 使用filter()函数,并将要过滤的迭代器对象和过滤函数作为参数传递进去,进行过滤,并返回过滤后的新列表。
例如,我们要从一个列表中挑出所有的偶数可以如下使用filter()函数:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 定义过滤函数,返回列表中所有的偶数
def even_filter(num):
if num % 2 == 0:
return True
else:
return False
result = filter(even_filter, numbers)
print(list(result)) # [2, 4, 6, 8, 10]
在这里,even_filter()函数被定义为处理函数,它接收一个整数,如果该整数是偶数,它返回True,否则返回False。filter()函数能够接受一个列表,并使用even_filter()函数对其每个元素进行过滤,最终返回由满足条件的元素组成的列表。
另外,filter()函数的过程也可以使用Lambda函数来简化,例如:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = filter(lambda x : x % 2 == 0, numbers) print(list(result)) # [2, 4, 6, 8, 10]
在这里,我们使用了Lambda函数来代替even_filter()函数,实现了同样的功能。
除了列表,filter()函数也可以使用于字典、元组、集合等其他序列类型,例如:
# 使用filter()函数过滤字典
scores = {'Alice': 90, 'Bob': 80, 'Cathy': 70, 'Dave': 60, 'Eva': 50}
passed_students = dict(filter(lambda x : x[1] >= 70, scores.items()))
print(passed_students) # {'Alice': 90, 'Bob': 80, 'Cathy': 70}
# 使用filter()函数过滤元组
students = [('Alice', 90), ('Bob', 80), ('Cathy', 70), ('Dave', 60), ('Eva', 50)]
passed_students = list(filter(lambda x : x[1] >= 70, students))
print(passed_students) # [('Alice', 90), ('Bob', 80), ('Cathy', 70)]
在这些例子中,我们分别使用了dict()和list()函数将filter()函数返回的结果转换为字典和列表。
需要注意的是,filter()函数返回的不是一个列表,而是一个迭代器对象。如果需要获得过滤后的值,需要使用list()函数将迭代器转换成列表。
总之,filter()函数是Python中十分常用的一个函数,它能够对列表和其他序列类型中的元素进行过滤,并返回一个新列表。可以通过定义一个处理函数或Lambda函数来实现过滤功能。
