功能
- 用于对容器中的元素进行过滤处理
- 用 iterable 中函数 function 返回真的那些元素,构建一个新的迭代器。
语法
filter(function, iterable)
参数:
- function - 测试 iterable 元素是否返回 true 或 false 的函数
- iterable - 要过滤的 iterable,可以是集合、列表、元组或任何迭代器的容器
如果 function 是 None ,则会假设它是一个身份函数,即 iterable 中所有返回假的元素会被移除。
返回值:
- filter() 方法返回一个迭代器(filter 对象),该迭代器通过了 iterable 中每个元素的函数检查,返回的是原序列中的值,非布尔值。
- 另外,如果未定义函数时,相当于操作if <元素>,即:
[*filter(None,[1,False,3])]
# [1, 3]
原理
- 在调用filyer()函数时,iterable会被遍历,它的元素会被逐一传入function()函数中
- function()函数如果返回true,则元素被保留;否则元素被丢弃
- 最后遍历完成,已经保留的元素被放到一个新的容器数据中
filter 对象
以值为偶数(除以2时余数为0)时返回 True 的 lambda(匿名函数)为例:
l = [-2, -1, 0, 1, 2]
print(filter(lambda x: x % 2 == 0, l))
# <filter object at 0x10bb38580>
print(type(filter(lambda x: x % 2 == 0, l)))
# <class 'filter'>
返回 filter 型的对象,即使直接 print(),也不输出内容的值,可以用 for 循环等方式取出来。
for i in filter(lambda x: x % 2 == 0, l):
print(i)
# -2
# 0
# 2
示例
# 筛选大于 5 的值
f = filter(lambda x: x>5, [2,3,5,7,9])
f # <filter at 0x7fe33ea36730>
list(f)
# [7, 9]
# 函数为 None
f = filter(None, [2,False,5,None,9])
list(f)
# [2, 5, 9]
列表表达式
l = [-2, -1, 0, 1, 2]
[x for x in l if x % 2 == 0]
# [-2, 0, 2]
[x for x in l if x % 2 != 0]
# [-1, 1]
l_s = ['apple', 'orange', 'strawberry']
[x for x in l_s if x.endswith('e')]
# ['apple', 'orange']
[x for x in l_s if not x.endswith('e')]
# ['strawberry']
l = [-2, -1, 0, 1, 2]
[x for x in l if x]
# [-2, -1, 1, 2]
l_2d = [[0, 1, 2], [], [3, 4, 5]]
[x for x in l_2d if x]
# [[0, 1, 2], [3, 4, 5]]