Python 中filter函数用法

时间:2022-06-20 18:26:01

filter()和map一样,接收一个函数和一个序列。和map不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素

过滤出奇数:

def   is_odd(n):
return n%2==1

print filter(is_odd,[1,2,3,4,5]) # ==>[1, 3, 5]

 过滤掉空字符串:

def   not_empty(s):
return s and s.strip()

print filter(not_empty,['A','','B',None,'C',' ']) # ==>['A', 'B', 'C']

 

L=range(1,101)
def iseven(x):
return x%2==0

print filter(iseven,L)
#[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]