美文网首页
Python基础-filter函数详解

Python基础-filter函数详解

作者: Python学习驿站 | 来源:发表于2023-08-09 09:48 被阅读0次

在Python中,filter()是一个内置函数,用于根据指定条件筛选可迭代对象中的元素,并返回一个新的可迭代对象,其中包含满足条件的元素。

filter()函数的语法如下:

filter(function, iterable)

其中,function是一个用于筛选的函数,iterable是一个可迭代对象,可以是列表、元组、集合等。

filter()函数的工作原理如下:

  1. 对可迭代对象中的每个元素,依次调用function函数,并传递该元素作为参数。
  2. 如果function函数返回值为True,则将该元素保留到结果中;如果返回值为False,则将该元素过滤掉。
  3. 最后,filter()函数返回一个新的可迭代对象,其中包含满足条件的元素。

以下示例演示了filter()函数的用法:

# 筛选出列表中的偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(filtered_numbers))
>>> [2, 4, 6, 8, 10]

# 筛选出字符串列表中长度大于3的字符串
words = ["apple", "banana", "car", "dog", "elephant"]
filtered_words = filter(lambda x: len(x) > 3, words)
print(list(filtered_words))
>>> ['apple', 'banana', 'elephant']

# 过滤掉Python中布尔值是False的对象,比如长度为0的对象(如空列表或空字符串)或在数字上等于0的对象。
words = [11, False, 18, 21, "", 12, 34, 0, [], {}]
filtered_words = filter(None, words)
print(list(filtered_words))
>>> [11, 18, 21, 12, 34]

在上述示例中,我们使用了匿名函数(lambda函数)作为function参数来定义筛选条件。您也可以使用自定义函数来替代匿名函数。

需要注意的是,filter()函数返回的结果是一个迭代器,若需要使用列表或其他容器类型,可以通过将返回值转换为列表来实现,如list(filter(...))

更★多★知★识★请★关★注★同★名★∨

相关文章

网友评论

      本文标题:Python基础-filter函数详解

      本文链接:https://www.haomeiwen.com/subject/vnbopdtx.html