Python函数:如何使用filter函数?
Python的filter函数是一种很有用的函数,它可以通过一个函数将一个可迭代对象中的元素过滤出来,并返回一个符合条件的新的可迭代对象。在本文中,我们将介绍filter函数的详细用法和示例,以及如何使用它来过滤出符合条件的元素。
filter函数的用法
filter函数的语法如下:
filter(function, iterable)
其中function是一个判断函数,用于筛选元素,iterable是一个可迭代对象,可以是列表、元组、集合、字典等。
function函数返回值为True或False,如果返回True,则保留该元素,否则丢弃该元素。
filter函数的返回值是一个迭代器,包含经过筛选后的元素。
示例代码:
# filter函数示例
scores = [89, 97, 58, 72, 100, 80, 75, 66]
def is_pass(score):
# 判断是否及格
return score >= 60
# 使用filter函数过滤出及格分数
pass_scores = list(filter(is_pass, scores))
print(pass_scores)
输出结果:
[89, 97, 72, 100, 80, 75, 66]
上面的示例代码中,我们定义了一个列表scores,用于存储学生的成绩,然后定义了一个函数is_pass,用于判断分数是否及格。最后使用filter函数过滤出及格的分数,得到一个新的列表pass_scores。
示例代码中,filter函数的 个参数是is_pass函数,第二个参数是scores列表。filter函数会遍历scores列表中的每个元素,对每个元素调用is_pass函数判断是否及格,如果及格则保留该元素,否则丢弃。最后返回一个新的列表pass_scores。
如果不使用filter函数,可以使用for循环实现相同的功能:
# 不使用filter函数示例
scores = [89, 97, 58, 72, 100, 80, 75, 66]
def is_pass(score):
# 判断是否及格
return score >= 60
# 使用for循环过滤出及格分数
pass_scores = []
for score in scores:
if is_pass(score):
pass_scores.append(score)
print(pass_scores)
输出结果与上面的示例代码相同。
filter函数的实际应用
filter函数可以应用于多种情况,例如:
1. 过滤出所有偶数
示例代码:
# 过滤出所有偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def is_even(number):
# 判断是否为偶数
return number % 2 == 0
# 使用filter函数过滤出偶数
even_numbers = list(filter(is_even, numbers))
print(even_numbers)
输出结果:
[2, 4, 6, 8]
2. 删除所有空字符串
示例代码:
# 删除所有空字符串 words = ['hello', 'world', '', 'python', '', ''] # 使用filter函数删除空字符串 non_empty_words = list(filter(lambda x: x != '', words)) print(non_empty_words)
输出结果:
['hello', 'world', 'python']
3. 过滤出所有年龄大于18岁的人
示例代码:
# 过滤出所有年龄大于18岁的人
people = [{'name': '张三', 'age': 23},
{'name': '李四', 'age': 18},
{'name': '王五', 'age': 28},
{'name': '赵六', 'age': 15}]
# 使用filter函数过滤出年龄大于18岁的人
adults = list(filter(lambda x: x['age'] > 18, people))
print(adults)
输出结果:
[{'name': '张三', 'age': 23}, {'name': '王五', 'age': 28}]
4. 过滤出所有奇数
示例代码:
# 过滤出所有奇数 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] # 使用filter函数过滤出奇数 odd_numbers = list(filter(lambda x: x % 2 == 1, numbers)) print(odd_numbers)
输出结果:
[1, 3, 5, 7, 9]
5. 过滤出所有非空列表
示例代码:
# 过滤出所有非空列表 items = ['hello', [1, 2, 3], '', [], [4, 5, 6], None, [7, 8, 9]] # 使用filter函数过滤出非空列表 non_empty_lists = list(filter(lambda x: isinstance(x, list) and x != [], items)) print(non_empty_lists)
输出结果:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
总结
filter函数是Python中非常有用的一个函数,它可以通过一个函数过滤出符合条件的元素,并返回一个新的可迭代对象。在实际应用中,filter函数可以用于多种场景,例如过滤出偶数、删除空字符串、过滤出年龄大于18岁的人等。需要注意的是,filter函数返回的是一个迭代器,需要使用list等函数将其转换为列表或其他可迭代对象。
