Home > database >  Using 'not in' with an if statement inside a for loop in python
Using 'not in' with an if statement inside a for loop in python

Time:12-13

I have 2 lists. First list has a few sentences as strings. The second list has a few words as strings. I want to iterate through the list of words, and if none of the words are in a sentence from the first list, I want to add it to a counter. Following is the code I wrote:

    sentences = [
    "Wow, what a great day today!! #sunshine",
    "I feel sad about the things going on around us. #covid19",
    "This is a really nice song. #linkinpark",
    "The python programming language is useful for data science",
    "Why do bad things happen to me?",
    "Apple announces the release of the new iPhone 12. Fans are excited.",
    "Spent my day with family!! #happy",
]

words = ['great', 'excited', 'happy', 'nice', 'wonderful', 'amazing', 'good', 'best']

counter = 0

for sentence in sentences:
    for word in words:
        if word not in sentence:
            counter  = 1
print(counter)

Instead of printing 3, it prints 52.

I understand what it's doing, it's checking for each word, and if it's not in the sentence, it's counting that sentence multiple times for each word that's not in the sentence.

But I can't figure out how to make it do what I want it to do. Any help will be greatly appreciated!

All the details are above.

CodePudding user response:

for sentence in sentences:
    counter  = 1
    for word in words:
        if word in sentence:
            counter -= 1
            break

This would do the trick. As long as no word is found in the sentence, the counter is increased. If a word is found, that counter is reversed.

CodePudding user response:

You can use all() (or any()) builtin function to check if all words are not in the sentence:

out = 0
for sentence in sentences:
    out  = all(word not in sentence for word in words)

print(out)

Prints:

3

Or one-liner:

out = sum(all(word not in sentence for word in words) for sentence in sentences)
print(out)
  • Related