Filter 函数
filter(function, iterable)
让 function 对 iterable 的每个元素求值,保留返回 True 的元素。
返回一个 惰性 filter 对象(迭代器)。
nums = [1, 2, 3, 4, 5, 6]
even = filter(lambda x: x % 2 == 0, nums)
print(list(even)) # [2, 4, 6]
等价于:保留为 True 的元素。
假值包括:0, False, ‘’, None, [], {}, set()
items = [0, 1, "", "hi", None, "abc"]
print(list(filter(None, items)))
# ['hi', 'abc', 1]
def is_long(s):
return len(s) > 3
words = ["hi", "hello", "cat", "python"]
result = filter(is_long, words)
print(list(result))
# ['hello', 'python']
过滤掉 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}]
去空字符串
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))
nums = range(50)
result = list(filter(lambda x: x % 2 == 0 and x > 10 and x < 40, nums))
print(result)
# [12, 14, ..., 38]
不会执行,直到消费:
f = filter(lambda x: x > 3, [1, 2, 3, 4, 5])
print(next(f)) # 4
print(next(f)) # 5
你已经学过惰性 -> 这就是那一类对象。
filter 写法
list(filter(lambda x: x > 3, arr))
列表推导(更可读)
[x for x in arr if x > 3]
复杂过滤场景 -> 推荐列表推导
明确的布尔判断 -> 推荐 filter
根据 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}]
| 场景 | 是否适合 |
|---|---|
| 数据清洗(去 None / 空值) | ✅︎ 非常适合 |
| 过滤数组或字典列表 | ✅ 非常高频 |
| 惰性加载大数据 | ✅ 性能好 |
| 复杂过滤逻辑 | ❌ 列表推导更可读 |
| 一步处理多序列 | ❌ 用 map 更合适 |