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

2024-09-29 18:42:16 发布

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

在我的代码中,我试图将“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']

Tags: 字符串inalpha列表dataifismatch
2条回答

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

应该是这样的:

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中的多个字符串中查找匹配项。使用布尔值应该可以完成这项工作。如果您还有其他问题,请告诉我们

试着列出理解力:

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

相关问题 更多 >

    热门问题