在我的代码中,我试图将“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']
您不想从正在迭代的列表中删除元素。相反,您可以添加一个条件来验证匹配的单词是否已添加到输出列表中
应该是这样的:
我还删除了
break
关键字,因为它们可能会阻止代码在data
中的多个字符串中查找匹配项。使用布尔值应该可以完成这项工作。如果您还有其他问题,请告诉我们试着列出理解力:
相关问题 更多 >
编程相关推荐