Python 匹配两个列表之间的列表元素中的部分字符串

Python matching partial strings in list elements between two lists

在我的代码中,我尝试将 'match' 中的项目与 'data' 列表中的字符串相匹配。

我希望代码查看 'match' 列表中的第一个单词,如果它与数据 'list' 中的字符串匹配,那么它将被添加到另一个列表中。 我想做的第二个检查是 'match' 列表中的前两个单词是否与 data.

中的字符串匹配

目前我的输出只给我一个 water12 的实例 - 而两个都应该被拾取。

有人可以让我知道我可能哪里出错了吗?


match =['f helo','happy hellp','floral', 'alpha','12133','water12 puppies']
data=['f we are', 'hello there', 'alpha beta','happy today is the case','112133 is it', 'floral is my fave', 'water12 if healthy','water12 puppies are here and exist']

lst=[]
for i in match:
    for j in data:
        if i.split()[0] in j:
            lst.append(j)
            data.remove(j)
            break
        if len(i) > 1:
            k= ' '.join(i.split()[:2])
            if k in j:
                lst.append(j) 
                data.remove(j)
                break
                
    else:
        lst.append(i + ' - not found')

print(lst)

期望的输出:

output= [ 'f we are', 'alpha beta','happy today is the case','112133 is it', 'floral is my fave', 'water12 if healthy','water12 puppies are here and exist']

尝试使用列表理解:

output = [x for x in data if any(True if z in x else False for z in x for y in match)]

您不想从迭代列表中删除元素。相反,您可以添加一个条件来验证匹配的词是否已添加到输出列表中。

应该是这样的:

lst = []
for i in match:
    has_match = False
    for j in data:
        if i.split()[0] in j:
            has_match = True
            print(i, j)
            if j not in lst:
                lst.append(j)
        if len(i) > 1:
            k = ' '.join(i.split()[:2])
            if k in j:
                has_match = True
                print(i, j)
                if j not in lst:
                    lst.append(j)
    if not has_match:
        lst.append(i + ' - not found')

我还删除了 break 关键字,因为它们可能会阻止您的代码在 data 中的多个字符串中查找匹配项。使用布尔值应该可以完成工作。如果您还有其他问题,请告诉我们。