2019年9月16日 / 204次阅读 / Last Modified 2019年9月16日
内置函数
Python内置的filter函数,实现了通过一个条件判断,将一个序列的所有元素进行过滤的功能。filter函数返回一个迭代器,通过此迭代器,可获得新的序列。网上找到一张图,很形象的说明了filter函数的功能:
filter函数不复杂,开始上代码:
>>> list(filter(lambda x:x%2 == 0, range(10)))
[0, 2, 4, 6, 8]
>>> list(filter(lambda x:x%3 == 0, range(30)))
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
>>> list(filter(lambda x:1==0, range(30)))
[]
上面代码最后一个示例,条件永为False,因此最后得到一个空list。如果filter函数第1个参数,即判断函数,为空,filter就不做任何过滤,返回原列表。
>>> list(filter(None, range(10)))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
再来一个case:
>>> a = ['abcde', 'kkk', 'ttt', 'apoe', 'opew']
>>> b = list(filter(lambda x:x.find('a')!=-1, a))
>>> b
['abcde', 'apoe']
lambda匿名函数在filter函数内非常好用,当然也可以使用别的函数来做更复杂的条件判断,只是要注意filter回调的函数,要返回True或者False:
>>> def tf(x):
... if x%2 == 0 and x > 0: return True
... else: return False
...
>>> a = [1,-1,2,-2,3,-3,4,-4,5,-5,6,-6]
>>> print(list(filter(tf,a)))
[2, 4, 6]
关于Python内置的filter函数,就写这些吧,主要是要多实践。
-- EOF --
本文链接:https://www.pynote.net/archives/1140
前一篇:tkinter中的cursor鼠标样式
后一篇:reduce函数
©Copyright 麦新杰 Since 2019 Python笔记