用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回True或者False,最后将返回True的元素放到新列表中。
>>> list(filter(lambda x:x%2,[1,2,3,4]))
[1, 3]
>>> list(filter(lambda x:x%2!=0,[1,2,3,4]))
[1, 3]
>>> list(filter(lambda x:x%2==0,[1,2,3,4]))
[2, 4]
>>> list(filter(lambda x:True,[1,2,3,4]))
[1, 2, 3, 4]
练习:只保留大写的。
方法一:
>>> def up(x):
... return x>="A" and x<="Z"
...
>>> list(filter(up,"AaBbCc"))
['A', 'B', 'C']
方法二:
>>> list(filter(lambda x:x >="A" and x<="Z","AaBbCc"))
['A', 'B', 'C']