KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I am looking for an efficient, pythonic way to apply multiple filters to a list of tuples. As an example, assume filters like this: def f1(t): return t[3]<10 def f2(t): return t[0]!=1 def f3(t): return t[1] in ("lisa","eric") def f4(t): return t[3]>2 And n-tuples (i.e. db-records) like this: tuples=[ (0,'tom','...',8), (1,'john','...',17), (2,'lisa','...',1), (3,'eric','...',18) ] The following works: def nFilter(filters,tuples): if filters and tuples: return nFilter(filters,filter(filters.pop(),tuples)) else: return tuples With results like: >>> nFilter([f1,f2,f3],tuples) [(2, 'lisa', '...', 1)] and >>> nFilter([f1,f2,f3,f4],tuples) [] But I'm wondering if there is a more direct way; what I had in mind is something like function composition (i.e f1(f2(...fn(tuples)...)) ), for an arbitrary list of functions. There are references to a functional library containing a compose function in the docs, but the links are all dead. Also, since I'm planning on using this on fairly large data sets, and possibly with a large number of filters in a production web service, it must be efficient, and I can't really say if this solution is. Any suggestions or improvements are welcome.
Tags (comma-separated)
Save Edits
Cancel