You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中是否存在可返回被过滤值的类filter拆分函数?

关于同时返回匹配/不匹配项的类filter函数说明

Python 生态里没有内置名为splitfilter的对应函数,但实现这个需求的方案非常成熟,完全可以满足把可迭代对象按判定规则拆成两部分的要求:

  • 最通用无依赖的方案:自己实现一个单次遍历的拆分函数,性能最优,只需要遍历一次序列就能完成分组,比两次调用filter、写两次列表推导的遍历效率高一倍,适配所有Python版本:
def splitfilter(predicate, iterable):
    matched, unmatched = [], []
    for item in iterable:
        if predicate(item):
            matched.append(item)
        else:
            unmatched.append(item)
    return matched, unmatched

# 对应拆分示例
a = [1, 3, 5, 7, 2, 4, 6]
lower, higher = splitfilter(lambda x: x < 5, a)
# 执行结果:lower = [1,3,2,4],higher = [5,7,6]
  • 如果你项目里已经引入了常用工具库more-itertools,或是使用Python 3.13及以上版本,可以直接用内置/库提供的partition函数,功能完全一致,注意它的返回值顺序是先返回不满足条件的元素迭代器,再返回满足条件的元素迭代器,不要把接收变量写反:
# Python 3.13+ 可以直接从标准库导入
# from itertools import partition
from more_itertools import partition

a = [1, 3, 5, 7, 2, 4, 6]
higher, lower = partition(lambda x: x < 5, a)
# 转列表后结果和上面的自定义函数完全一致

注意:不要为了写起来简短用两次列表推导分别筛选匹配、不匹配项,比如lower = [x for x in a if x<5]; higher = [x for x in a if x>=5],这种写法会遍历两次原序列,数据量较大时会有明显的性能浪费。

内容的提问来源于stack exchange,提问作者iHnR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 09:09:12