我想比較兩個列表,如果兩個列表都有與其匹配號碼相同的單詞。比賽號碼在這裏很重要。我是這樣做的;python中兩個列表的比較
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
,循環無限次地運行。如果在else
中打破for
循環,然後打破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
錯誤
使用set和&。 – YOU
將n = n + 1行移動到「if」條件之外的循環末尾。如果「如果」條件失敗,那麼n永遠不會增加,並且循環繼續進行 –
@ Dinesh.hmn請參閱編輯問題 – Humty