在我的代码中,我试图将“ match”项与“ data”列表中的字符串进行匹配。
我希望代码查看“匹配”列表中的第一个单词,如果它与数据“列表”中的字符串匹配,那么它将被添加到另一个列表中。我想做的第二项检查是“匹配”列表中的前两个单词是否与数据中的字符串匹配。
目前,我的输出仅给我一个水实例12-而这两个声音都已被拾取。
请有人让我知道我可能要去哪里了吗?
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']
您不想从要迭代的列表中删除元素。相反,您可以添加条件以验证匹配的单词是否已添加到输出列表中。
应该是这样的:
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
。使用布尔值即可完成工作。如果您还有其他问题,请告诉我们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句