filter()
函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,可以通过list()
转化为列表或者通过for
循环取值。
filter()
函数接收两个参数,第一个为函数,第二个为可迭代对象。返回序列中能使函数为真的元素的迭代器对象;如果函数为None
,则返回序列中值为True
的元素。
res = filter(None, [-1, 0, 1, 2, "abc", True, False, None])
print(list(res)) # [-1, 1, 2, 'abc', True]
需要注意的是,在python 3.x 和python 2.x 中,返回结果类型不同。执行如下代码:
res = filter(lambda x: x % 2 == 1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(type(res))
print(res)
在python 2.x 中返回结果为:
<type 'list'>
[1, 3, 5, 7, 9]
在python 3.x 中返回结果为:
<class 'filter'>
<filter object at 0x000001941835D0F0>
可以使用自定义的函数:
def is_odd(n):
"""过滤出列表中的奇数"""
return n % 2 == 1
res = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(list(res)) # [1, 3, 5, 7, 9]
通过for
遍历取值只能使用一次:
res = filter(lambda x: x % 2 == 1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
for i in res:
pass
print(res) # <filter object at 0x000002A083A6C0B8>
print(list(res)) # []
filter()
函数不只可以对数据进行过滤,还可以对字符串进行操作:
# 筛选出列表中以字母 a 开头的字符串
res = filter(lambda x: x.startswith('a'), ['abc', 'adsa', 'Def', 'Abd', ])
print(list(res)) # ['abc', 'adsa']
需要注意的是如果列表中有其他类型的元素,比如int
类型的数据,则会报错,因为int
类型的数据没有startswith
属性:
res = filter(lambda x: x.startswith('a'), [1, 'abc', 'adsa', 'Def', 'Abd', ])
print(list(res)) # AttributeError: 'int' object has no attribute 'startswith'