是否有一个与内置相对的过滤器()?

时间:2015-11-29 22:56:49

标签: python functional-programming

Python中是否有与filter相反的功能?即将项目保留在回调返回False的iterable中?无法找到任何东西。

5 个答案:

答案 0 :(得分:25)

不,filter()没有内置的反函数,因为你可以简单地反转测试。只需添加not

即可
positive = filter(lambda v: some_test(v), values)
negative = filter(lambda v: not some_test(v), values)

itertools模块确实有itertools.ifilterfalse(),这是相当多余的,因为反转布尔测试非常简单。 itertools版本始终作为生成器运行。

答案 1 :(得分:8)

您可以使用itertools.filterfalseMartijn建议执行此操作,将not放在您在过滤器中使用的lambda中的某个位置。

答案 2 :(得分:5)

另一种选择:

from operator import not_
compose = lambda f, g: lambda x: f( g(x) )

...

ys = filter(compose(not_, predicate), values)

您可以预先提供compose()的预展版本(例如功能正常或toolz)。

答案 3 :(得分:1)

Ross Bencina的评论Martijn Pieters' answer

  

你的推理不是很有说服力。第一种情况已经可以了   写的

positive = filter(some_test, values)
     

因此要求的至少应该像

一样简单
negative = filter(not(some_test), values)

我建议使用一个简单的否定包装函数:

def _not(func):
    def not_func(*args, **kwargs):
        return not func(*args, **kwargs)
    return not_func

允许写上面的第二行(添加了下划线或其他区别,因为not运算符不能也可能不应该被覆盖):

negative = filter(_not(some_test), values)

答案 4 :(得分:0)

我也有同样的情况,但是我不想为过滤器添加重复的功能。 这是我的解决方案,可以过滤字典中的项目并能够反转选择。

req_table = {
    "ID_4001" : {"R_STAT":True, "V_STAT":False, "TYPE":"X", "VEL": 1},
    "ID_0051" : {"R_STAT":True, "V_STAT":True,  "TYPE":"X", "VEL": 23},
    "ID_0741" : {"R_STAT":True, "V_STAT":False, "TYPE":"Y", "VEL": 32},
    "ID_0701" : {"R_STAT":True, "V_STAT":False, "TYPE":"X", "VEL": 2353},
}

def count_prop(prop, with_val, rq_table, invert=False):
    return len(list(filter(lambda tc : (tc[1][prop] == with_val)^invert, rq_table.items())))

print("Items of type X: {}".format(count_prop("TYPE", "X", req_table)))
print("Items of type Y: {}".format(count_prop("TYPE", "X", req_table, invert=True)))

诀窍是^,它充当启用的not

相关问题