【问题标题】:Python matching partial strings in list elements between two listsPython匹配两个列表之间列表元素中的部分字符串
【发布时间】:2020-10-31 17:05:39
【问题描述】:

在我的代码中,我试图将“匹配”中的项目与“数据”列表中的字符串相匹配。

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

目前我的输出只给了我一个 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']

【问题讨论】:

    标签: python python-3.x for-loop if-statement nested-loops


    【解决方案1】:

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

    应该是这样的:

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

    【讨论】:

    • 非常感谢!我不知道你能做到这一点,而且将来会很有帮助。
    • 嗯,也许你的列表中有一个浮点数?
    • 对不起,是的!我删除了“nan”。再次感谢您!
    • 您可以在has_match=True 之后添加print(i, j)
    • 实际上,您可以通过创建元组列表将这两个项目添加到列表中。您可以创建一个空列表data = [],然后将print 语句替换为data.append((i, j))。在你的代码末尾,如果你想要一个pandas.DataFrame,你可以做dataframe = pandas.DataFrame(data, columns=['Pattern', 'Matched String']
    【解决方案2】:

    尝试使用列表理解:

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

    【讨论】:

    • 谢谢,但这不起作用 - 我得到了 ['hello there', 'water12 puppies are here and exist'] 作为不正确的输出
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多