mardi 28 mars 2017

filtering a list of text strings by a list of word strings

i have a list of strings, each consisting out of several words called happenings. A second list called mostcom20 contains strings which each consist only out of one word.

My goal is to filter out all strings of the first list that do not contain at least one word of the second list.

I have:

happenings=["i have a dog","i want a dog","i like cats","i m hungry"]

mostcom20=["dog","cat"]

as a results i want a list like: newlist=["i have a dog","i want a dog","i like cats"]

This is the code i have:

newlist=[]
for s in happenings:
    for n in s.split():
        if n in mostcom20:
            newlist.append(s)
newlist

It doesnt give an error message. It returns an empty list. Anyone an idea why? Thank you for the help!

Aucun commentaire:

Enregistrer un commentaire