匹配列表中的多个单词

2024-06-12 13:05:00 发布

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

我正在分析包含成分的字符串。你知道吗

我把字符串分成一串单词 例如:

list1 = ['favorite','olive','oil']
list2 = ['favorite','oil']

我有一个配料表,我需要与列表中的单词匹配。例如

ingredients = ['sesame oil', 'olive oil', 'olive juice', 'oil']

我需要一个函数,在第一个场景中返回olive oil,在第二个场景中返回oil。你知道吗

任何提示和建议都非常感谢。你知道吗


Tags: 函数字符串列表场景单词favoritejuice成分
2条回答

很难理解你所说的“第一种情况”和“第二种情况”。这是相当含糊的。你知道吗

鉴于此,我同意你的建议。作为一个数据结构,最好的方法是按顺序将您的列表作为收藏夹,然后按顺序返回匹配成分的列表。如果非要我写这个,我可能会写得更像这样:

favorites = [['olive', 'oil'], ['oil']]
ingredients = ['sesame oil', 'olive oil', 'olive juice', 'oil']

def get_favorite_ingredients(favorite_list=[], ingred=[]):
    matched = []
    for fav in favorite_list:
        if ' '.join(fav) in ingred:
            matched.append(' '.join(fav))
    return matched

# this returns: ['olive oil', 'oil']
print get_favorite_ingredients(favorites, ingredients)

这样就可以很清楚地按照数组的顺序排列,第一个位置是第一个最重要的收藏,第二个位置是第二个最重要的收藏,等等。。。不管有多少种最爱和多少种配料,只要最爱的列表是按照你希望的顺序排列的,同样的顺序总是会被退回。希望这有帮助!你知道吗

这将提供其中一个列表和成分之间重叠的列表。如果列表中有多个项目在一组配料中,这可能很有用。你知道吗

def ingredient_checker(checklist):
    ingredients = ['sesame oil', 'olive oil', 'olive juice', 'oil']
    return [item for item in set(checklist).intersection(ingredients)]

>>> list3 = ['favorite','olive','oil', 'olive juice']
>>> ingredient_checker(list3)
['oil', 'olive juice']

相关问题 更多 >