【发布时间】:2013-10-04 06:03:44
【问题描述】:
假设我有一个迭代起来非常昂贵的数据结构,我需要根据某些标准将它的元素收集到列表中。
#fake data. pretend it's hard to access
import random
slowStruct = range(30)
random.shuffle(slowStruct)
def check1(x):
return x < 3
def check2(x):
return x > 15
def check3(x):
return x < 25 and x > 20
最简单的方法是使用列表推导。但这需要对结构进行 3 次迭代:
res1 = [node for node in slowStruct if check1(node)]
res2 = [node for node in slowStruct if check2(node)]
res3 = [node for node in slowStruct if check3(node)]
更快的方法是使用循环并附加到结果列表:
res1 = []
res2 = []
res3 = []
for node in slowStruct:
if check1(node):
res1.append(node)
if check2(node):
res2.append(node)
if check3(node):
res3.append(node)
是否有一个函数式编程结构或习语可以执行多个过滤器,同时只使用一次迭代?
我可以想象它看起来像:
res1, res2, res3 = multiFilter(preds=[check1, check2, check3], iterable=slowStruct)
【问题讨论】:
标签: python filter functional-programming