4

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

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 Answers 3

10
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.

Sign up to request clarification or add additional context in comments.

1 Comment

actually, inspectorG4dget's solution worked for another case. In mine, this is the best. Thank you very much.
8

You can do:

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

Comments

7

Why not a set intersect?

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

9 Comments

Clever (+1), but again, don't use a list, use a tuple. (There's no reason for a list here and a tuple is faster to generate)
and actually, set(data).intersection(("word1","word2","word3")) might be slightly faster as there is no need to create 2 sets for this operation.
@mgilson: I seem to be off my game with the formatting today. Thank you for cleaning up my posts (I believe this is the 2nd or 3rd one today that you have fixed the formatting in)
Note that this won't work if data was a string containing "word1", "word2", etc., as substrings (which it might have been based on the OP's code).
There is one performance implication: the intersection of two sets does not shortcut in the same way as any. This is probably not an issue here.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.