Python中使用filter函数的10个示例
发布时间:2023-06-29 21:50:10
filter函数是Python内置的一个高阶函数,它接受一个函数和一个可迭代对象作为参数,然后返回一个根据函数筛选出来的新的可迭代对象。下面是10个使用filter函数的示例。
1. 过滤出偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) # 输出:[2, 4, 6, 8, 10]
2. 过滤出长度为3的字符串
words = ['apple', 'orange', 'banana', 'kiwi', 'grape'] filtered_words = list(filter(lambda x: len(x) == 3, words)) print(filtered_words) # 输出:['kiwi']
3. 过滤出大于10的数
numbers = [1, 12, 5, 9, 15, 7, 18, 3, 21] filtered_numbers = list(filter(lambda x: x > 10, numbers)) print(filtered_numbers) # 输出:[12, 15, 18, 21]
4. 过滤掉小于零的数
numbers = [-1, 5, -3, 0, 8, -10, 2] filtered_numbers = list(filter(lambda x: x >= 0, numbers)) print(filtered_numbers) # 输出:[5, 0, 8, 2]
5. 过滤出奇数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] odd_numbers = list(filter(lambda x: x % 2 != 0, numbers)) print(odd_numbers) # 输出:[1, 3, 5, 7, 9]
6. 过滤出首字母为'a'的单词
words = ['apple', 'orange', 'banana', 'kiwi', 'grape'] filtered_words = list(filter(lambda x: x[0] == 'a', words)) print(filtered_words) # 输出:['apple']
7. 过滤出包含元音字母的单词
words = ['apple', 'orange', 'banana', 'kiwi', 'grape'] vowels = ['a', 'e', 'i', 'o', 'u'] filtered_words = list(filter(lambda x: any(vowel in x for vowel in vowels), words)) print(filtered_words) # 输出:['apple', 'orange', 'kiwi', 'grape']
8. 过滤出长度大于5并且包含字母'm'的单词
words = ['apple', 'orange', 'banana', 'kiwi', 'grape'] filtered_words = list(filter(lambda x: len(x) > 5 and 'm' in x, words)) print(filtered_words) # 输出:['banana']
9. 过滤出能被3整除的数
numbers = [1, 3, 5, 9, 12, 15, 21] filtered_numbers = list(filter(lambda x: x % 3 == 0, numbers)) print(filtered_numbers) # 输出:[3, 9, 12, 15, 21]
10. 过滤掉空字符串
words = ['', 'apple', 'orange', '', 'banana'] filtered_words = list(filter(lambda x: x != '', words)) print(filtered_words) # 输出:['apple', 'orange', 'banana']
以上是10个使用filter函数的示例,它们展示了如何使用filter函数根据特定的条件对可迭代对象进行过滤。根据实际的需求,通过定义不同的lambda函数和不同的条件,可以灵活地使用filter函数进行数据筛选和处理。
