python函数之filter函数

本文介绍了Python内置函数filter的使用方法,包括当函数参数为None和指定函数时的不同行为。通过多个示例展示了如何使用filter结合lambda表达式进行数据筛选。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python函数之filter函数


实例环境

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:40:30) [MSC
v.1500 64 bit ( AMD64)] on win32
Type “help”, “copyright”, “credits” or “license” for more information.


>>> help(filter)
Help on built-in function filter in module __builtin__:

filter(...)
    filter(function or None, sequence) -> list, tuple, or string

    Return those items of sequence for which function(item) is true.
    If function is None, return the items that are true.  If sequence
    is a tuple or string, return the same type, else return a list.

filter参数的参数:第一个是函数对象或者None,第二个是序(sequence),如果第一个参数 是一个函数对象,则将第二个参数(可迭代的序列)作为函数参数传入函数,函数执行并把返回ture
的之筛选出来,并成一个同传入序列同类型的序列,如果第一个参数为None,则将第二个参数 里面为Ture的值筛选出


实例一:

当第一个参数为None时,筛选出第二个参数列表中元素符合True的值,并且以同类型的序列打包返回

>>> filter(None,[1,2,0,False,True])
[1, 2, True]

返回的值为列表类型

>>> t = filter(None,[1,2,0,False,True])
>>> type(t)
<type 'list'>
>>> t
[1, 2, True]

实例二:

将filter函数直接以迭代器的形式应用

>>> for i in filter(None,[1,2,0,False,True]):
...     print i
...
1
2
True

实例三:

当第一个参数为一个函数时

>>> def odd(x):
...     return x % 2
...
>>> t2 = filter(odd, range(10))
>>> t2
[1, 3, 5, 7, 9]
>>

实例四:

filter函数与lambda函数表达式的结合应用

>>> t3 = filter(lambda x : x % 2,range(10))
>>> t3
[1, 3, 5, 7, 9]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JaysenLeo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值