欢迎访问宙启技术站
智能推送

使用Python filter()函数的10个示例

发布时间:2023-05-30 08:40:30

Python中的filter()函数被用于过滤一个序列,生成包含满足某些特定条件的元素的一个新序列。它返回一个迭代器对象,也可以用list()方法从迭代器中创建一个列表。

下面是使用Python filter()函数的10个实际示例:

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) # Output: [2, 4, 6, 8, 10]

2. 过滤奇数

numbers = [1,2,3,4,5,6,7,8,9,10]
odd_numbers = list(filter(lambda x: x%2!=0, numbers))
print(odd_numbers) # Output: [1, 3, 5, 7, 9]

3. 过滤空字符串

words = ["hello", "", "world", "", "python"]
filtered_words = list(filter(lambda x: x != "", words))
print(filtered_words) # Output: ["hello", "world", "python"]

4. 过滤长度小于3的字符串

words = ["hi", "hello", "world", "python"]
filtered_words = list(filter(lambda x: len(x)>=3, words))
print(filtered_words) # Output: ["hello", "world", "python"]

5. 过滤负数

numbers = [-1,-2,3,4,-5,6,7,-8,9,10]
positive_numbers = list(filter(lambda x: x>0, numbers))
print(positive_numbers) # Output: [3, 4, 6, 7, 9, 10]

6. 过滤大写字符串

words = ["hello", "WORLD", "Python", "CODING"]
lowercase_words = list(filter(lambda x: x.islower(), words))
print(lowercase_words) # Output: ["hello"]

7. 过滤包含"a"的字符串

words = ["cat", "dog", "apple", "banana", "ant"]
filtered_words = list(filter(lambda x: "a" in x, words))
print(filtered_words) # Output: ["cat", "apple", "banana", "ant"]

8. 过滤为空的数据

data = ["hello", None, "world", "", "python", 0, False, [], {}]
filtered_data = list(filter(lambda x: x is not None and x != "" and x != 0 and x != False and x != [] and x != {}, data))
print(filtered_data) # Output: ["hello", "world", "python"]

9. 过滤包含元音字母的字符串

words = ["cat", "dog", "apple", "banana"]
filtered_words = list(filter(lambda x: any(char in "aeiou" for char in x), words))
print(filtered_words) # Output: ["cat", "apple", "banana"]

10. 过滤小于5的元素

numbers = [1,2,3,4,5,6,7,8,9,10]
filtered_numbers = list(filter(lambda x: x>=5, numbers))
print(filtered_numbers) # Output: [5, 6, 7, 8, 9, 10]

以上是10个使用Python filter()函数的示例,这个函数是Python高阶函数中最常用的函数之一,可以使代码更简洁、易读且高效。