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

Python中的内置函数:filter()的使用方法

发布时间:2023-06-03 13:44:31

Python中的内置函数filter()可以对可迭代对象中的每个元素进行筛选,返回一个新的可迭代对象,其中只包含符合条件的元素。

filter()函数的语法为:

filter(function, iterable)

其中,function是一个用来过滤元素的函数,iterable是可迭代对象。function接受一个参数,代表一个可迭代对象中的元素,返回值为布尔值。当function返回True时,该元素会被保留到新的可迭代对象中。

下面通过一些实例来说明filter()函数的用法。

### 根据条件筛选数字

假设有一个数字列表,需要将其中大于等于5的数字筛选出来,可以使用lambda表达式作为function参数传入filter()函数:

numbers = [3, 7, 2, 8, 9, 4, 5]
result = filter(lambda x: x >= 5, numbers)
print(list(result))  # 输出[7, 8, 9, 5]

### 去除列表中的空字符串

假设有一个字符串列表,需要将其中的空字符串去掉,可以使用bool函数作为function参数传入filter()函数,因为空字符串转换为bool值为False:

strings = ['hello', '', 'world', ' ', '  ', 'python']
result = filter(bool, strings)
print(list(result))  # 输出['hello', 'world', 'python']

### 根据条件筛选字典

假设有一个字典列表,需要将其中年龄大于等于20岁的人筛选出来,可以使用lambda表达式作为function参数传入filter()函数:

people = [{'name': '张三', 'age': 18},
          {'name': '李四', 'age': 22},
          {'name': '王五', 'age': 25},
          {'name': '赵六', 'age': 17}]
result = filter(lambda x: x['age'] >= 20, people)
print(list(result))  # 输出[{'name': '李四', 'age': 22}, {'name': '王五', 'age': 25}]

### 根据字符串长度筛选元组

假设有一个元组列表,需要将其中长度大于等于3的字符串筛选出来,可以使用len函数结合lambda表达式作为function参数传入filter()函数:

tuples = [('apple', 'red'), ('banana', 'yellow'), ('orange', 'orange'), ('pear', 'green')]
result = filter(lambda x: len(x[0]) >= 3, tuples)
print(list(result)) # 输出[('apple', 'red'), ('banana', 'yellow'), ('orange', 'orange')]

总的来说,filter()函数是Python中一个非常强大、常用的内置函数,它可以方便地进行筛选、过滤操作。