Skip to main content
 首页 » 编程设计

python之评估 python 中字符串中子字符串存在的最佳性能方法

2025年05月04日20虾米哥

我知道我能做到:

word = 'shrimp' 
sentence = 'They eat shrimp in Mexico, and even more these days' 
word in sentence 

因此它会评估 True。

但是如果我有:

words = ['a','la','los','shrimp'] 

如何评估句子是否包含任何words元素?

我关心性能,因为列表可能很大,我不想使用循环来扩展代码行

请您参考如下方法:

可以读成英文。但可能不是最高效的。首先进行基准测试,然后仅在需要时使用优化的解决方案。

any(word in sentence for word in words) 

any如果任何元素为 True,则返回 True,否则返回 False。 (word in sentence for word in words) 是一个可迭代对象,它生成每个单词是否在句子中。