利用Python中的filter()函数过滤数据。
发布时间:2023-06-22 22:11:43
Python语言中的 filter() 函数是一种内置函数,提供了一种方便的方法来过滤数据。借助这个函数,我们可以更快地过滤掉一个可迭代对象(todo)中的不必要的数据,以便于我们最终得到我们需要的数据。
filter(function, list) 函数接受回调函数和待处理的序列作为参数。filter()函数对序列中的元素依次执行前面的函数,最后返回一个 bool 值为 True 的序列中的元素集合。
下面是一个简单的示例,使用 filter() 函数有一个列表,过滤掉里面所有为奇数的数字:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = filter((lambda x: x % 2 == 0), numbers) print(list(even_numbers))
运行这个程序会输出 [2, 4, 6, 8, 10]。这段代码中,我们首先定义了包含一组数字的列表,然后用 filter() 函数过滤掉了其中所有奇数值的元素,最后以列表的形式输出了结果。
这个示例展示了 Python 过滤数据的基本流程,但是 filter() 函数的应用场景远不止如此。下面将展示更多的过滤数据的示例:
1. 使用 filter() 函数筛选包含指定字符的单词
words = ["apple", "banana", "cherry", "pineapple", "mango"] filtered_words = filter((lambda x: 'a' in x), words) print(list(filtered_words))
2. 删除列表中的空字符串
words = ["hello", "world", "", "goodbye", "cruel", "world"] filtered_words = filter((lambda x: x != ''), words) print(list(filtered_words))
3. 提取字典中特定键值对的字典
dictionaries = [
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 25},
{'name': 'Charlie', 'age': 35},
{'name': 'David', 'age': 29},
{'name': 'Ethan', 'age': 27}
]
filtered_dictionaries = filter((lambda x: x['age'] > 28 and x['age'] < 35), dictionaries)
print(list(filtered_dictionaries))
4. 提取列表中长度大于或等于指定值的字符串
words = ["apple", "banana", "pear", "cherry", "kiwi"] filtered_words = filter((lambda x: len(x) >= 5), words) print(list(filtered_words))
总之,Python 过滤函数 filter() 是一种强大而灵活的工具,可以帮助我们轻松地过滤掉不必要的数据,并获取我们所需的数据,以最大程度地提高代码的简洁性。
