Shyam Sunder
Shyam Sunder

Reputation: 1240

Applying a list of functions to a single variable

I'm applying three filters to a single data structure that holds my data one after the other. Can I do this more neatly? Like a single call to a class encapsulating the three filters or passing it from one filter to the other (more like a co-routine) The latter looks rather scary so can I do it neatly with the former paradigm?

Example, data_list holds my data

def _filter1(elem):
    return elem < 0        

def _filter2(element):
    ...
def _filter3(element):
    ...

list = filter(_filter1,list)
list = filter(_filter2,list)
list = filter(_filter3,list)

I imagine this would be the simplest way to put it:

filters = [_filter1, _filter2, _filter3]
list = apply_filters(*filters)

Thank you.

Upvotes: 1

Views: 88

Answers (3)

ecatmur
ecatmur

Reputation: 157484

You can do it with functools.reduce:

from functools import reduce
list = reduce(lambda acc, pred: filter(pred, acc), filters, list)

Upvotes: 3

Andrew Clark
Andrew Clark

Reputation: 208695

Using a list comprehension:

lst = [x for x in lst if _filter1(x) and _filter2(x) and _filter3(x)]

Using a function that combines all of the filters:

def apply_filters(lst, *filters):
    def _filter(elem):
        return all(f(elem) for f in filters)
    return filter(_filter, lst)

lst = apply_filters(lst, _filter1, _filter2, _filter3)

As a side note, don't use list as a variable name as it will mask the built-in.

Upvotes: 0

Nicolas
Nicolas

Reputation: 5678

filters = (_filter1, _filter2, _filter3)
list_after = filter(lambda x: all(f(x) for f in filters), your_list)

Upvotes: 1

Related Questions