Avi*_*ohn 13 python functional-programming
Python中的函数是否与其相反filter?即将项目保留在回调返回的iterable中False?找不到任何东西.
Mar*_*ers 25
不,没有内置的反函数filter(),因为你可以简单地反转测试.只需添加not:
positive = filter(lambda v: some_test(v), values)
negative = filter(lambda v: not some_test(v), values)
Run Code Online (Sandbox Code Playgroud)
该itertools模块确实具有itertools.ifilterfalse()相当多余的功能,因为反转布尔测试非常简单.该itertools版本始终作为生成器运行.
从Ross Bencina的评论到Martijn Pieters的回答:
你的推理不太有说服力。第一种情况已经可以写了
Run Code Online (Sandbox Code Playgroud)positive = filter(some_test, values)因此所要求的至少应该是简单的
Run Code Online (Sandbox Code Playgroud)negative = filter(not(some_test), values)
我建议使用一个简单的否定包装函数:
def _not(func):
def not_func(*args, **kwargs):
return not func(*args, **kwargs)
return not_func
Run Code Online (Sandbox Code Playgroud)
允许按上面的方式编写第二行(添加下划线或其他区别,因为not运算符不能而且可能不应该被覆盖):
negative = filter(_not(some_test), values)
Run Code Online (Sandbox Code Playgroud)
另外一个选项:
from operator import not_
compose = lambda f, g: lambda x: f( g(x) )
...
ys = filter(compose(not_, predicate), values)
Run Code Online (Sandbox Code Playgroud)
您可以预先compose()提供可用的版本(例如,在功能或工具中).
| 归档时间: |
|
| 查看次数: |
8192 次 |
| 最近记录: |