Python中filter()函数的使用方式及示例方法
发布时间:2023-06-21 06:04:35
Python中filter()函数是一种内置函数,用于过滤序列中的元素。该函数需要两个参数, 个是一个函数,第二个是一个可迭代的序列。
语法:filter(function, iterable)
其中,function为一个函数,该函数用于对iterable中的每个元素进行判断,如果返回值为True,则保留该元素,否则过滤掉。
示例1:过滤掉序列中的偶数
假如我们有一个包含1到10数字的列表,现在需要过滤掉其中的偶数,只保留奇数。
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def is_odd(num):
return num % 2 != 0
res = filter(is_odd, nums)
print(list(res)) # [1, 3, 5, 7, 9]
以上代码定义了一个函数is_odd,用于判断是否为奇数,然后使用filter函数对nums列表进行过滤,最后打印出结果。
示例2:过滤掉字符串列表中长度小于等于3的字符串
strings = ['apple', 'cat', 'banana', 'dog', 'egg']
def is_long_enough(s):
return len(s) > 3
res = filter(is_long_enough, strings)
print(list(res)) # ['apple', 'banana']
以上代码中,首先定义了一个函数is_long_enough,用于判断字符串的长度是否大于3,然后使用filter函数对strings字符串列表进行过滤,最后打印出结果。
示例3:过滤掉由字典组成的列表中,字典中某个键为None的字典
students = [
{'name': 'Tom', 'age': 18},
{'name': 'Jerry', 'age': 20, 'gender': 'male'},
{'name': 'Bob', 'age': 22, 'gender': 'female'},
{'name': 'Alice', 'age': 19, 'gender': None}
]
def has_gender(d):
if 'gender' not in d or d['gender'] is None:
return False
else:
return True
res = filter(has_gender, students)
print(list(res)) # [{'name': 'Jerry', 'age': 20, 'gender': 'male'}, {'name': 'Bob', 'age': 22, 'gender': 'female'}]
以上代码中,首先定义了一个函数has_gender,用于判断字典中是否存在某个键为gender且其值不为None,然后使用filter函数对students字典列表进行过滤,最后打印出结果。
总结:filter()函数可以对序列中的元素进行过滤,通过传递一个函数来确定过滤规则,最后返回一个由过滤后的元素组成的新序列。
