How to check whether a string exists in a list python

3639 views python
-1

I want to compare word by word whether the word exists in the list.

items=["michael jackson","nintendo"]
aa = ["i think michael jackson is cool","i love nintendo"]


for i, a in zip(items, aa):
    token=a.split()

    for x in token:

        if x in i:
            print "X: " + x

Output:

X: i
X: michael
X: jackson
X: i
X: nintendo

Expected output:

X: michael
X: jackson
X: nintendo

As you can see, "i" is also printed out because "i" is in "michael" and "nintendo", but i do not want that. Note that I want to compare words by words in "items" and "aa", by comparing the items in the same index.

answered question

Why do you want to compare "michael" and "jackson" separately?

I believe this is what you're looking for.

2 Answers

3

for item in items:
  if item in aa:
    return True

It's a pretty simple solution. To check a string for a smaller string, just use in

posted this
12

You don't need to use split. Its very simple. Try:

items=["michael jackson","nintendo"]
aa = ["i think michael jackson is cool","i love nintendo"]


for x in aa.split(" "):
    if x in items:
        print "X: " + x

posted this

Have an answer?

JD

Please login first before posting an answer.