检查列表中的每个元素是否与Python中的字符串匹配?

时间:2021-10-08 13:42:15

I am writing a simple if else loop to check if a string match with multiple words like this:

我正在编写一个简单的if else循环来检查字符串是否与多个单词匹配,如下所示:

if "word1" in data or "word2" in data or "word3" in data:
    ....

I am not sure if we have a more comprehensive way to process this kind of comparison ?

我不确定我们是否有更全面的方法来处理这种比较?

Thank you very much

非常感谢你

3 个解决方案

#1


8  

if any(word in data for word in ('word1', 'word2', 'word3')):
    ...

If you run into performance issues, you may want to convert data to a set before running the comparisons.

如果遇到性能问题,可能需要在运行比较之前将数据转换为集合。

#2


8  

You can do:

你可以做:

if any(x in data for x in ('word1', 'word2', 'word3')):

#3


6  

Why not a set intersect?

为什么一组不相交?

if set(["word1", "word2","word3"]) & set(data):
    # do stuff!

#1


8  

if any(word in data for word in ('word1', 'word2', 'word3')):
    ...

If you run into performance issues, you may want to convert data to a set before running the comparisons.

如果遇到性能问题,可能需要在运行比较之前将数据转换为集合。

#2


8  

You can do:

你可以做:

if any(x in data for x in ('word1', 'word2', 'word3')):

#3


6  

Why not a set intersect?

为什么一组不相交?

if set(["word1", "word2","word3"]) & set(data):
    # do stuff!