我有一个列表,其中我希望返回每个列表中与特定关键字匹配的字符串的内容
这是原始列表:
list_orig = [['summary of the', 'cold weather', 'bother me over high'], ['what is in a name?', 'reveals a lot', 'juniper relationship']]
要应用此关键字搜索:
keywords = ['summary', 'indicates','suggesting', 'relationship', 'reveals']
期望的结果:
list_refine = [['summary of the'], ['reveals a lot', 'juniper relationship']]
到目前为止,我有适用于单个列表的代码,但我不知道如何查看所有列表。 下面是一个列表的代码:
string1 = list_orig
substr1 = keywords
def Filter(string, substr):
return [str for str in string if
any(sub in str for sub in substr)]
print(Filter(string1, substr1))
以下是1个列表的结果:
['summary of the']
我研究了很多方法来循环列表。这里有一次尝试
for item in string3:
new.append([])
for item in items:
item = Filter(string1, substr1)
new[-1].append(item)
item
刚拿到一张空白名单 谢谢大家!感谢:)
您可以使用for循环遍历列表,使用另一个for循环遍历项目和关键字,如下所示
这里有一个没有显式循环的替代解决方案
相关问题 更多 >
编程相关推荐