Python:在不同条件下匹配字符串

时间:2018-11-08 03:48:37

标签: python if-statement match

我有4个列表:

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']

我想知道string1中的每个字符串都属于哪个组,如果字符串是关于水果的,则忽略它,如果字符串是关于学校和家庭的,则打印它们。

我期望的结果:

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

这是我的代码,它确实打印出了我想要的东西,但是有很多重复的值:

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)

我知道这不是找到匹配项的有效方法。如果您有任何建议,请告诉我。谢谢!

2 个答案:

答案 0 :(得分:1)

您可以结合使用anyfilter来做到这一点。我们使用any来忽略在no中出现任何单词的字符串。否则,我们使用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):
        first_match = list(filter(lambda x: x in s, school + home))[0]
        print(s)
        print(first_match)

输出

I have no school today
school
Baking pies at home
Baking

答案 1 :(得分:0)

假设您要尝试查看列表1,学校和家庭中是否有任何一个在string1的任何字符串中的单词。

我只会将否,然后将学校和家庭名单合并在一起

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

希望这会有所帮助,我无法对其进行测试,但这是我最好的选择,而无需进行测试以查看是否可行:)