Skip to main content
Documents
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Filter 函数

✅ filter():核心概念

filter(function, iterable)

让 function 对 iterable 的每个元素求值,保留返回 True 的元素

返回一个 惰性 filter 对象(迭代器)。

✅ 1. 基本示例:过滤偶数

nums = [1, 2, 3, 4, 5, 6]

even = filter(lambda x: x % 2 == 0, nums)
print(list(even))  # [2, 4, 6]

✅ 2. 若 function 为 None -> 过滤掉“假值”

等价于:保留为 True 的元素。

假值包括:0, False, ‘’, None, [], {}, set()

items = [0, 1, "", "hi", None, "abc"]

print(list(filter(None, items)))
# ['hi', 'abc', 1]

✅ 3. 使用自定义函数过滤

def is_long(s):
    return len(s) > 3

words = ["hi", "hello", "cat", "python"]

result = filter(is_long, words)
print(list(result))  
# ['hello', 'python']

✅ 4. filter + 字典(常用)

过滤掉 price < 10 的股票:

stocks = [
    {"code": "600001", "price": 9.5},
    {"code": "600002", "price": 12},
]

cheap = list(filter(lambda s: s["price"] < 10, stocks))
print(cheap)
# [{'code': '600001', 'price': 9.5}]

✅ 5. filter + 数据清洗(真实业务最佳用法)

去空字符串

items = ["A", "", " ", "B", "C"]

valid = list(filter(lambda s: s.strip(), items))
print(valid)  # ['A', 'B', 'C']

去掉 None 数据

cleaned = list(filter(lambda x: x is not None, data))

✅ 6. filter + 多条件过滤

nums = range(50)

result = list(filter(lambda x: x % 2 == 0 and x > 10 and x < 40, nums))
print(result)
# [12, 14, ..., 38]

✅ 7. filter 是“惰性的”

不会执行,直到消费:

f = filter(lambda x: x > 3, [1, 2, 3, 4, 5])

print(next(f))  # 4
print(next(f))  # 5

你已经学过惰性 -> 这就是那一类对象。

✅ 8. filter 与列表推导式的对比

filter 写法

list(filter(lambda x: x > 3, arr))

列表推导(更可读)

[x for x in arr if x > 3]

复杂过滤场景 -> 推荐列表推导

明确的布尔判断 -> 推荐 filter

✅ 9. 实战:股票数据筛选

根据 code 前缀 + 金额过滤:

stocks = [
    {"code": "600001", "price": 9.5},
    {"code": "300200", "price": 22},
    {"code": "600002", "price": 15},
]

filtered = list(filter(
    lambda s: s["code"].startswith("600") and s["price"] > 10,
    stocks
))

print(filtered)

输出:

[{'code': '600002', 'price': 15}]

🎯 总结:filter 的典型使用场景

场景 是否适合
数据清洗(去 None / 空值) ✅︎ 非常适合
过滤数组或字典列表 ✅ 非常高频
惰性加载大数据 ✅ 性能好
复杂过滤逻辑 ❌ 列表推导更可读
一步处理多序列 ❌ 用 map 更合适