skip to Main Content

I want to filter a list of lists passing variable set of conditions but not one by one. Is there any way to pass a whole list of conditions to the filter function and extract the desired list of values based on condition?
Here is my code:

profiles = [
    ['Rose Winds', 'Cloud Computing', 'USA', 6.5, 5000, 5, 'F'],
    ['Merry Brown', 'Cloud Computing', 'UK', 5, 7000, 5, 'F'],
    ['Abdul Fazil', 'Big Data', 'Australia', 11, 8000, 4, 'M'],
    ['Chris Janes', 'Big Data', 'Ireland', 7, 2500, 4, 'M'],
    ['Lina Mesro', 'Cyber Security', 'Malaysia', 7, 6500, 4, 'F'],
    ['Sireen May', 'Artificial Intelligence', 'Australia', 0, 4000, 4, 'F'],
    ['Jine Tims', 'Robotics', 'Australia', 0, 3500, 3, 'M'],
    ['Niki Rohdes', 'Artificial Intelligence', 'China', 9, 8500, 5, 'F']
]

europe = ["UK", "Ireland", "Germany", "Scotland"]


def from_europe():
    ls = []
    for profile in profiles:
        for country in europe:
            if country in profile:
                ls.append(country)
    return ls


def make_conditions(**kwargs):
    fields = {
        'name': 0,
        'specialization': 1,
        'country': 2,
        'experience': 3,
        'salary': 4,
        'qualification': 5,
        'gender': 6
    }

    def filter_func(elt):
        for k, v in kwargs.items():
            if elt[fields[k]] != v:
                return False
            else:
                return True
    return filter_func


result = list(filter(make_conditions(country=from_europe()), profiles))
print(result)

When I give condition like country='UK' etc, then it works properly but when I try to pass a list of conditions like country=["UK", "Ireland", "Germany", "Scotland"], then it give me an empty list…
Anyone help me please??

2

Answers


  1. When you pass a list country=["UK", "Ireland", "Germany", "Scotland"]

    if elt[fields[k]] != v
    

    becomes

    if 'USA' != ["UK", "Ireland", "Germany", "Scotland"]
    

    I would do something like:

    if isinstance(v, str) and elt[fields[k]] == v:
        return True
    elif elt[fields[k]] in v:
        return True
    else:
        return False # prefer to return 'False' by default
    

    Then run

    result = list(filter(make_conditions(country=europe), profiles))
    # [['Merry Brown', 'Cloud Computing', 'UK', 5, 7000, 5, 'F'], ['Chris Janes', 'Big Data', 'Ireland', 7, 2500, 4, 'M']]
    

    If you just want to filter by country, the other answer is better.

    Login or Signup to reply.
  2. Do you mean something like:

    [p for p in profiles if p[fields['country']] in europe]
    

    Note: for faster processing, make europe a set instead of a list.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search