我知道我能做到:
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/