python内置函数——filter()函数

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'
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值