Python:匹配列表中两个字符串中的单词

Python:匹配列表中两个字符串中的单词,python,Python,我想匹配两个字符串中的同一个单词 代码: 因为berry出现在“berry:blueberry”和“blueberry and raspberry”中,所以我想让first match同时打印这两个,但它不起作用 然后我尝试了另一种编码方式: nn=['berry blueberry','blueberry and raspberry','banana vs. apple','apple is delicious'] #k=['benz','x5'] category=['blueberry',

我想匹配两个字符串中的同一个单词

代码:

因为berry出现在“berry:blueberry”和“blueberry and raspberry”中,所以我想让first match同时打印这两个,但它不起作用

然后我尝试了另一种编码方式:

nn=['berry blueberry','blueberry and raspberry','banana vs. apple','apple is delicious']
#k=['benz','x5']
category=['blueberry','cherry']
for i in range(len(nn)):
    for s in category:
        if any(x in s for x in nn[i]):
            first_match = list(filter(lambda x: x in s, nn[i]))[0]
            print(first_match)
它印刷了:

b
e
b
e
b
e
l
e
输出错误。我期望的结果是打印:

blueberry
blueberry

下面是代码的一个变体,用于提取
nn
中的匹配值:

nn=['berry: blueberry','blueberry and raspberry',
    'banana vs. apple','apple is delicious']
category=['blueberry','cherry']
for s in category:
    matches = [x for x in nn if s in x]
    print(matches)

我想你可以从中得到你想要的打印输出。诀窍在于对比赛的列表理解;缺少的部分是如何进行正确的if检查。

您可以在操作符中使用
,如下所示:

berries = [s for s in nn if 'berry' in s]
浆果被设置为
[“浆果:蓝莓”、“蓝莓和覆盆子”]

如果要使用类别,可以执行以下操作:

category=['blueberry','banana']
fresh_fruit = [s for c in category for s in nn if c in s]

fresh_fruit
将被设置为
['berry:blueberry','blueberry and raspberry','banana vs.apple']

你能描述一下你的代码是做什么的,你期望什么吗?@ZisIsNotZis我做了,但我再次编辑了它。如果有整个
的话(x在s代表x在nn[I]):…
块只要做
如果s在nn[I]:打印
category=['blueberry','banana']
fresh_fruit = [s for c in category for s in nn if c in s]