背景
给定两个字符串列表string_list和substr_list,筛选出string_list中包含substr_list中元素的所有字符串。
示例:
Input : string_list= ['city1', 'class5', 'room2', 'city2']
substr_list= ['class', 'city']
Output : ['city1', 'class5', 'city2']
Input : string_list= ['coordinates', 'xyCoord', '123abc']
substr_list = ['abc', 'xy']
Output : ['xyCoord', '123abc']
方法1:
逐个判断:
def list_filter(string, substr):
return [str for str in string if
any(sub in str for sub in substr)]
string_list = ['city1', 'class5', 'room2', 'city2']
substr_list = ['class', 'city']
print(list_filter(string_list, substr_list))
输出结果:
['city1', 'class5', 'city2']