假设我有一个关键词列表:terms = ["dog","cat","fish"]我还有另一个列表,其中包含更长的文本字符串:texts = ["I like my dog", "Hello world", "Random text"]我现在想要我有一个代码,它基本上遍历列表texts并检查它是否包含列表中的任何项目terms,并且它应该返回一个列表,其中包含文本中的此项是否匹配。这是代码应该产生的:result = ["match","no match","no match"]
1 回答
梦里花落0921
TA贡献1772条经验 获得超6个赞
以下是如何使用zip()和列表理解:
terms = ["dog","cat","fish"]
texts = ["I like my dog", "Hello world", "Random text"]
results = ["match" if a in b else "no match" for a,b in zip(terms,texts)]
print(results)
输出:
['match', 'no match', 'no match']
更新:结果证明压缩不是 OP 想要的。
terms = ["dog","cat","fish"]
texts = ["I like my dog", "Hello world", "Random text"]
results = ["match" if any(b in a for b in terms) else "no match" for a in texts]
print(results)
输出:
['match', 'no match', 'no match']
添加回答
举报
0/150
提交
取消