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

2024-05-04 08:35:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有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)

我知道这不是找到匹配的有效方法。如果你有什么建议,请告诉我。谢谢您!你知道吗


Tags: noinapplehomefortodayifhave
2条回答

假设您试图查看列表no、school和home中是否有一个单词位于string1中的任何字符串中。你知道吗

我只是把学校和家庭的名单连在一起

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

希望这对我有所帮助,我不能测试它,但这是我最好的选择,不用做测试,看看它是否有效:)

您可以使用^{}^{}的组合来实现这一点。我们使用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

相关问题 更多 >