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

Python中filter()函数的使用方式及实例

发布时间:2023-06-02 04:58:51

Python中的filter()函数是用来筛选序列中的元素,返回一个所有元素都为真值的新序列。可以用来过滤掉不需要的数据。

filter()函数的语法如下:

filter(function, iterable)

其中,function是一个函数,iterable是一个可迭代对象(列表、元组、集合、字典)。

function这个函数接收一个参数,如果该参数满足条件,就返回True,否则返回False。filter()函数将可迭代对象iterable的每个元素传递给function函数进行判断,最终返回一个新的迭代器,其中包含iterable中所有满足条件的元素。

下面是一些示例:

示例1:过滤出列表中的偶数

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def is_even(x):
    return x % 2 == 0

even_numbers = list(filter(is_even, numbers))

print(even_numbers)

输出:

[2, 4, 6, 8, 10]

示例2:过滤掉列表中的空字符串

words = ['hello', '', 'world', '', 'python', '']

def is_nonempty(s):
    return s != ''

nonempty_words = list(filter(is_nonempty, words))

print(nonempty_words)

输出:

['hello', 'world', 'python']

示例3:将字典中所有值为空字符串的键过滤出来

person = {'name': 'Alice', 'age': 20, 'gender': '', 'email': '', 'phone': '1234567890'}

empty_values = list(filter(lambda v: v == '', person.values()))

empty_keys = list(filter(lambda k: person[k] == '', person.keys()))

print(empty_values)
print(empty_keys)

输出:

['', '']
['gender', 'email']

以上是filter()函数的使用方式及实例,希望可以帮助大家更好地理解该函数的用法。