Python filter() 函数允许您根据指定的条件从可迭代对象中过滤掉元素。如果对象允许通过迭代检索其项(例如列表、元组或字符串),则称该对象是可迭代的。
filter() 函数将条件应用于可迭代对象的每个元素,并检查哪个元素满足给定条件。基于此,它创建了一个新的可迭代对象,仅包含满足条件的那些元素。
filter() 是内置函数之一,不需要任何模块。
语法
Python filter() 函数的语法如下所示 -
filter(function, iterable)
参数
Python filter() 函数接受两个参数 -
- function − 它指定一个条件,根据该条件过滤掉可迭代对象的元素。
- iterable − 它表示一个对象,例如列表、字符串或元组。
返回值
Python filter() 函数返回一个新的可迭代对象。
filter() 函数示例
练习以下示例来理解 Python 中 filter() 函数的使用:
示例:filter() 函数的基本用法
以下示例显示了 Python filter() 函数的基本用法。在这里,此函数接受 lambda 表达式和 list 对象,以从指定列表中筛选出偶数。
numerics = [59, 22, 71, 65, 12, 6, 19, 28, 17, 5]
lstOfevenNums = list(filter(lambda x: (x % 2 == 0), numerics))
print("The list of even numbers from the list:")
print(lstOfevenNums)
当我们运行上述程序时,它会产生以下结果——
The list of even numbers from the list:
[22, 12, 6, 28]
[22, 12, 6, 28]
示例:从字符串中筛选元音
在下面的代码中,我们定义了一个用户定义的函数,该函数将作为参数传递给 filter() 函数,以检查和分隔指定字符串中的元音。
def checkVowel(chars):
vowelsLst = 'aeiou'
return chars in vowelsLst
orgnlStr = "Tutorials Point"
newVowels = ''.join(filter(checkVowel, orgnlStr))
print("The vowels from the given string:")
print(newVowels)
以下是上述代码的输出 -
The vowels from the given string:
uoiaoi
uoiaoi
示例:从列表中删除假值
如果我们将 None 作为函数参数传递,filter 函数将从可迭代对象中删除所有被视为 false 的元素。Python 中的一些 Falsy 值是 “”、0、False 等。以下代码说明了相同的 -
dataLst = [55, "", None, "Name", "Age", 25, None]
newLst = list(filter(None, dataLst))
print("The new list without None value:")
print(newLst)
上述代码的输出如下 -
The new list without None value:
[55, 'Name', 'Age', 25]
[55, 'Name', 'Age', 25]
示例:从字典中筛选记录
在下面的代码中,将创建一个字典。然后使用 filter() 函数删除 id 小于 100 的元素。
employees = [
{"name": "Ansh", "id": 121},
{"name": "Vivek", "id": 100},
{"name": "Tapas", "id": 93}
]
newLst = list(filter(lambda x: (x['id'] >= 100), employees))
print("The new list with id greater than or equal to 100:")
print(newLst)
以下是上述代码的输出 -
The new list with id greater than or equal to 100:
[{'name': 'Ansh', 'id': 121}, {'name': 'Vivek', 'id': 100}]
[{'name': 'Ansh', 'id': 121}, {'name': 'Vivek', 'id': 100}]