我需要写一个函数,通过多个条件过滤一个字符串列表。
如果我只用一个条件,就会是这样的。
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
但是,这个函数必须是动态的,所以对于2个参数,列表的理解会是这样的。
small_list = [el for el in inputlist if filter_ in el and filter_2 in el]
这当然不是动态的。
传递一个列表作为单一参数会导致一个错误。
TypeError: 'in <string>' requires string as left operand, not list
我怎么能这样做?
如果我理解正确的话,这就是你的函数。
def get_newest(inputlist, filters):
return [x for x in inputlist if all(f in x for f in filters)]
filters
是一个过滤器的可迭代,例如 ['substr1', 'substr2']
.