Python: Match string in different conditions

2966 views python
-1

I have 4 lists:

string1=['I love apple', 'Banana is yellow', "I have no school today", "Baking pies at home", "I bought 3 melons today"]
no=['strawberry','apple','melon', 'Banana', "cherry"]
school=['school', 'class']
home=['dinner', 'Baking', 'home']

I want to know every sting in string1 belongs to which group, if the string is about fruit, then ignore it, if string is about school and home, print them.

The result I expected:

I have no school today
school
Baking pies at home
Baking #find the first match

Here's my code, it did print out something I want, but with many duplicate values:

for i in string1:
    for j in no:
        if j in i:
            #print(j)
            #print(i)
            continue
        for k in school:
            if k in i:
                print(i)
                print(k)
            for l in home:
                if l in i:
                    print(i)
                    print(l)

I know this is not an efficient way to find the match. If you have any suggestion please let me know. Thank you!

answered question

2 Answers

3

Assuming you are trying to see if any of the lists no, school, and home have a word that is in any of the strings in string1.

I would just concatenate no, school and home lists together then just do

for string in string1:
    for word in all3lists:
        if word in string:
            print("{0}\n{1}".format(string, word))

Hope that is of some help, I'm not in a position to test it but that's my best bet without doing a test to see if that works :)

posted this
3

You can do this with a combination of any and filter. We use any to ignore strings that have any occurrence of a word in no. Otherwise, we find the match using filter:

string1=['I love apple', 'Banana is yellow', "I have no school today", "Baking pies at home", "I bought 3 melons today"]
no=['strawberry','apple','melon', 'Banana', "cherry"]
school=['school', 'class']
home=['dinner', 'Baking', 'home']

for s in string1:
    if not any(x in s for x in no):
        y = list(filter(lambda x: x in s, school + home))[0]
        print(y)
        print(s)

Output

school
I have no school today
Baking
Baking pies at home

posted this

Have an answer?

JD

Please login first before posting an answer.