Python:高阶函数-filter

大数据学习路线图

【版权声明】博客内容由厦门大学数据库实验室拥有版权,未经允许,请勿转载!版权所有,侵权必究!
[返回Python教程首页]

filter()

filter()也是Python常用的内置函数,用于过滤序列。与map()类似,fiter()也是接收两个参数:一个函数和一个序列,将函数作用在序列的每一个元素上,根据函数返回值True或False,来决定是否舍弃该元素,最终返回一个迭代器,内容是原序列的子序列。例如:

  1. def is_even(x):
  2. return x % 2 == 0
  3. l = filter(is_even,[0,1,2,3,4,5])
  4. print(l)
  5. for var in l: #for循环遍历迭代器l
  6. print(var)
Python

执行结果:

  1. <filter object at 0x7f14037fcc50>
  2. 0
  3. 2
  4. 4
Python

下面我们用匿名函数的形式来使用filter函数。
例1:给定一系列字符串元组,筛选出包含python的所有字符串。

  1. str_tuple = ("hipython","pyth","lovepython","PYTHON","XMU")
  2. result = filter((lambda x:x.find("python")!=-1), str_tuple)
  3. for str in result:
  4. print(str)
Python

输出结果:

hipython
lovepython

例2:给定一系列字符串元组,筛选出长度为5的字符串。

  1. str_list = ["abcde","12345","python","xmu","hello"]
  2. result = filter((lambda x:len(x)==5), str_list)
  3. for str in result:
  4. print(str)
Python

输出结果:

abcde
12345
hello