Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a list of lists based on a variable set of conditions with Python?

Question related to this post.

I need help to filter a list of lists depending on a variable set of conditions.

Here is an extract of the list:

ex = [
    # ["ref", "type", "date"]
    [1, 'CB', '2017-12-11'],
    [2, 'CB', '2017-12-01'],
    [3, 'RET', '2017-11-08'],
    [1, 'CB', '2017-11-08'],
    [5, 'RET', '2017-10-10'],
]

I want to apply a final treatment like list(filter(makeCondition, ex)) where makeCondition(myList, **kwargs) function returns a boolean that enables to filter the list.

I have troubles building this function as adviced in this post, as the number of conditions defined in the **kwargs dictionnary is variable.

Examples of conditions sets:

conditions = {"ref": 3}
conditions = {"ref": 1, "type": "CB"}

Here is a start:

def makeConditions(myList, **p):

    # For each key:value in the dictionnary
    for key, value in p.items():

        if key == "ref":
            lambda x: x[0] == value
        elif key == "type":
            lambda x: x[1] == value
        elif key == "date":
            lambda x: x[2] == value

    # return chained conditions...

list(filter(makeConditions, ex))

I don't get the logical idea that various comments attempted to give in the post mentioned above... Do I have to execute the filter() function for each sublist or is it possible to do it for the whole global list? Any advices will be very welcome!

like image 449
wiltomap Avatar asked Dec 11 '25 15:12

wiltomap


1 Answers

I would simply make a function that returns the conditional:

def makeConditions(**p):
    fieldname = {"ref": 0, "type": 1, "date": 2 }
    def filterfunc(elt):
        for k, v in p.items():
            if elt[fieldname[k]] != v: # if one condition is not met: false
                return False
        return True
    return filterfunc

Then you can use it that way:

>>> list(filter(makeConditions(ref=1), ex))
[[1, 'CB', '2017-12-11'], [1, 'CB', '2017-11-08']]
>>> list(filter(makeConditions(type='CB'), ex))
[[1, 'CB', '2017-12-11'], [2, 'CB', '2017-12-01'], [1, 'CB', '2017-11-08']]
>>> list(filter(makeConditions(type='CB', ref=2), ex))
[[2, 'CB', '2017-12-01']]
like image 65
Serge Ballesta Avatar answered Dec 13 '25 03:12

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!