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
When you pass a list
country=["UK", "Ireland", "Germany", "Scotland"]
becomes
I would do something like:
Then run
If you just want to filter by
country
, the other answer is better.Do you mean something like:
Note: for faster processing, make
europe
aset
instead of alist
.