我想比较两个列表,如果两个列表的匹配编号都相同。匹配号码在这里很重要。我是这样做的。
List1= ['john', 'doe','sima']
List2=[]
test = "John is with Doe but alina is alone today."
List2 = test.lower().split()
n=0
counter=0
while n < len(List1):
for i in range(len(List2)):
if List1[n] == List2[i]:
print("Matched : "+str(counter) + List1[n])
n=n+1
counter=counter+1
else:
print("No match :"+ List1[n])
# break
# break
如果两个列表都有匹配的单词,则程序运行正常。但是对于不匹配的单词
sima
,循环将运行无限次。如果中断for
中的else
循环,然后按照代码中的注释指示立即断开while
循环,则该程序仅运行第一个匹配项。提前致谢。编辑1
while n < len(List1):
for i in range(len(List2)):
# print("Matching :"+ List1[n]+ " : "+ List2[i])
if List1[n] == List2[i]:
print("Matched : "+str(counter) + List1[n])
counter=counter+1
else:
print("No match :"+ List1[n])
n=n+1
给出
IndexError: list index out of range
错误 最佳答案
从您的代码,这将起作用。虽然这不是最优雅的编写方式,但这是您的代码
List1= ['john', 'doe','sima']
List2=[]
test = "John is with Doe but alina is alone today."
List2 = test.lower().split()
n=0
counter=0
while n < len(List1):
for i in range(len(List2)-1):
if List1[n] == List2[i]:
print("Matched : "+str(counter) + List1[n])
counter=counter+1
else:
print("No match :"+ List1[n])
n=n+1
这就是你的结果
Matched : 0john
No match :john
No match :john
No match :john
No match :john
No match :john
No match :john
No match :john
No match :doe
No match :doe
No match :doe
Matched : 1doe
No match :doe
No match :doe
No match :doe
No match :doe
No match :sima
No match :sima
No match :sima
No match :sima
No match :sima
No match :sima
No match :sima
No match :sima