Python中的filter函数使用方法及示例
发布时间:2023-05-21 02:13:02
Python中的filter函数是一种对列表、元组、字典等进行筛选的方法,它可以过滤出符合条件的元素组成新的列表或迭代器。
filter函数的基本使用方法为:filter(function, iterable),其中function是一个返回值为布尔类型的函数,iterable是一个需要过滤的可迭代对象。
filter函数通过依次处理可迭代对象的每个元素,如果该元素符合function的条件,则将该元素加入新的列表或迭代器中。如果该元素不符合条件,则过滤掉该元素。
filter函数的返回值为一个迭代器,可以使用list()方法将其转为列表。
下面是一些使用filter函数的示例:
1.筛选出列表中的偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def is_even(num):
return num % 2 == 0
even_numbers = list(filter(is_even, numbers))
print(even_numbers) # [2, 4, 6, 8, 10]
2.筛选出字符串列表中长度为3的单词
words = ['apple', 'banana', 'car', 'dog', 'elephant', 'fish']
def is_len3_word(word):
return len(word) == 3
len3_words = list(filter(is_len3_word, words))
print(len3_words) # ['car', 'dog']
3.筛选出字典列表中age为25以上的人
people = [{'name': 'Tom', 'age': 20},
{'name': 'Bob', 'age': 25},
{'name': 'Lisa', 'age': 30},
{'name': 'Mary', 'age': 40}]
def is_age25_or_above(person):
return person['age'] >= 25
age25_people = list(filter(is_age25_or_above, people))
print(age25_people) # [{'name': 'Bob', 'age': 25}, {'name': 'Lisa', 'age': 30}, {'name': 'Mary', 'age': 40}]
4.筛选出二维列表中元素为偶数的元素
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
def is_even_num(num):
return num % 2 == 0
even_nums = list(filter(is_even_num, [num for row in matrix for num in row]))
print(even_nums) # [2, 4, 6, 8]
总之,filter函数是Python中很实用的一种筛选方法,可以帮助我们快速过滤出符合条件的元素,节省了大量的时间和代码。
