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

标签 python string

我知道我能做到:

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) 是一个可迭代对象,它生成每个单词是否在句子中。

关于python - 评估 python 中字符串中子字符串存在的最佳性能方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22890122/

相关文章:

python - 正确 append

swift - 如何将币种代码重命名为币种全称? swift

c - 字符串存储到共享内存后无法正常显示

c++ - 具有不同编译器版本的 C++ 中的奇怪行为(字符串通过引用传递): See simple program illustration

Python类接口(interface)设计

python - 何时在 Pyramid 中使用route_url或route_path?

python - 如何使用 OpenCV 和 SIFT 查找训练图像的多个实例

python - 如何将 networkx 算法与我的自定义图形数据结构一起使用?

c++ - 将文件读入 C++ 中的字符串 vector 时,std::vector 下标超出范围

java - 如何在java中的正则表达式模式末尾分割字符串