0

I have a list of strings called keywords:

keywords = ["123", "hello there"]

I want to see if any of these strings are in this list strArr:

strArr = ["123", "hello there", "another"]

I've tried this:

if all (keyword in strArr for keyword in keywords):
    print("True")
else:
    print("False")

It works and returns true if I have the full string, but fails when I try to find a sub-string like so:

keywords = ["123", "hello"]

0

3 Answers 3

2

Anytime you have groups of things and you are testing membership/intersection etc, you should think about using sets. It is so much easier after you get started.

See the following example:

In [46]: keywords = {"123", "hello there"}                                                  
In [47]: strArr = {"123", "hello there", "another"}                                         
In [48]: keywords & strArr   # intersection                                                               
Out[48]: {'123', 'hello there'}
In [49]: keywords.issubset(strArr)                                                          
Out[49]: True
In [50]: if (keywords & strArr):  # do something

In the last line, if the intersection has anything in it, the value will be True, else it will be False.

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

Comments

1

You can check if each keyword is in any of the items in strArr:

print( all ( any( (keyword in strItem for strItem in strArr) ) for keyword in keywords ))

Note: if you are checking a condition and printing the result you could just print the condition itself.

Comments

1

Many people have already answered this question. Since I tried it, I will post my answer.

print ([i for i in strArr if any(j in keywords for j in i.split())]) # Outer For loop: "i for i in strArr", Inner For Loop with If any condition(): "if any(j in keywords for j in i.split())"

I hope this counts. :)

Comments

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.