测试列表中的任何项是否是另一个字符串列表的一部分

2024-06-16 10:22:50 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个关键词列表:

terms = ["dog","cat","fish"]

我还有另一个列表,其中包含更长的文本字符串:

texts = ["I like my dog", "Hello world", "Random text"]

我现在想要一个代码,它基本上遍历列表texts,检查它是否包含列表中的任何项目terms,并且它应该返回一个列表,其中包含文本中的该项目是否匹配

这是代码应该产生的结果:

result = ["match","no match","no match"]

Tags: 项目no字符串代码文本列表mymatch
1条回答
网友
1楼 · 发布于 2024-06-16 10:22:50

下面是如何使用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']

相关问题 更多 >