Reputation: 2095
I need to write a function that filters a list of strings by multiple conditions:
This would look this like this if I use one condition:
def get_newest(inputlist, filter_):
small_list = [el for el in inputlist if filter_ in el]
return small_list
smaller = get_newest(lines, "condition1")
smaller
However, the function has to be dynamic so the list comprehension would look like this for 2 arguments:
small_list = [el for el in inputlist if filter_ in el and filter_2 in el]
This is of course not dynamic.
Passing a list as a single argument results in an error:
TypeError: 'in <string>' requires string as left operand, not list
How can I do this?
Upvotes: 1
Views: 37
Reputation: 78760
If I understand correctly, this is your function.
def get_newest(inputlist, filters):
return [x for x in inputlist if all(f in x for f in filters)]
filters
is an iterable of filters, e.g. ['substr1', 'substr2']
.
Upvotes: 2