Python filter() 函数用于按条件过滤可迭代对象,保留使函数返回 True 的元素。
语法
filter(function, iterable)参数
function:判断函数,返回 True 保留。传 None 时过滤所有假值。第二个参数 iterable:要过滤的可迭代对象。
返回值
返回 filter 对象(迭代器),产出使函数为 True 的元素。要列表用 list()。
示例
nums = [1, 2, 3, 4, 5, 6]
def is_even(x):
return x % 2 == 0
print(list(filter(is_even, nums))) # [2, 4, 6]
# 用 lambda
print(list(filter(lambda x: x > 3, nums))) # [4, 5, 6]
# 过滤空串(利用真值)
words = ["hi", "", "world", "", "py"]
print(list(filter(None, words))) # ['hi', 'world', 'py']
# 过滤字符串列表
names = ["Tom", "Ann", "Bob"]
print(list(filter(lambda n: n.startswith("A"), names))) # ['Ann']输出:
[2, 4, 6]
[4, 5, 6]
['hi', 'world', 'py']
['Ann']注意事项
filter 返回迭代器,要列表用 list()。function 传 None 时过滤掉所有假值(0、空串、None)。列表推导式也能实现过滤。