python filter() 函数
函数定义
filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的迭代器对象。
该函数接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。
filter(function, iterable)
- function -- 判断函数。
- iterable -- 可迭代对象。
例子
过滤出列表中的所有奇数:
#!/usr/bin/python # -*- coding: UTF-8 -*- def is_odd(n): return n % 2 == 1 newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) print(list(newlist))
输出结果 :
[1, 3, 5, 7, 9]
过滤出1~100中平方根是整数的数:
#!/usr/bin/python # -*- coding: UTF-8 -*- import math def is_sqr(x): return math.sqrt(x) % 1 == 0 newlist = filter(is_sqr, range(1, 101)) print(list(newlist))
输出结果 :
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
用None过滤掉布尔值是False的对象
将None
作为filter()
的第一个参数,让迭代器过滤掉Python中布尔值是False
的对象。比如长度为0的对象(如空列表或空字符串)或在数字上等于0的对象。
aquarium_tanks = [11, False, 18, 21, "", 12, 34, 0, [], {}] filtered_tanks = filter(None, aquarium_tanks) print(list(filtered_tanks))
输出结果:
[11, 18, 21, 12, 34]