python中filter关键字

 

1、

filter()函数是一个过滤器,它的作用就是在海量的数据里面提取出有用的信息。

filter()这个内置函数有两个参数:第一个参数可以是一个函数也可以是None, 如果是一个函数的话,则将第二个可迭代对象里的每一个元素作为函数的参数进行计算,把返回True的值筛选出来;如果第一个参数是None,则直接将第二个参数中为True的值筛选出来。

第一个参数为None:

>>> temp = filter(None,[1,1,0,0,3,4,True,True,False,False,True])
>>> list(temp)
[1, 1, 3, 4, True, True, True]

 

第一个参数为函数:

>>> def a(x):
    return x % 2

>>> temp = filter(a,range(20))
>>> list(temp)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> def a(x):
    return x / 2 > 5

>>> temp = filter(a,range(20))
>>> list(temp)
[11, 12, 13, 14, 15, 16, 17, 18, 19]

 

2、与lambda表达式结合

>>> temp = filter(lambda x:x % 2, range(20))
>>> list(temp)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> temp2 = filter(lambda x: x / 2 > 5, range(20))
>>> list(temp2)
[11, 12, 13, 14, 15, 16, 17, 18, 19]

 

posted @ 2021-03-08 15:55  小鲨鱼2018  阅读(234)  评论(0编辑  收藏  举报