python中两种列表的比较

python中两种列表的比较,python,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 ran

我想比较两个列表,如果它们都有相同的单词和匹配号。比赛号码在这里很重要。我是这样做的

    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

给出
索引器错误:列表索引超出范围
错误

该问题是由一个小问题引起的。在
if
正文中增加
n
,这意味着如果满足条件,则增加变量。在您的情况下,当到达
sima
时,该条件不满足,因此n不会增加。因此,您需要在循环的
之后增加
n

从您的代码中,这将起作用。虽然不是最优雅的编写方式,但下面是您的代码

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

虽然你的问题的解决方案已经被其他人回答了,但它仍然不优雅。正如你在问题中提到的,匹配号很重要,所以我给你我解决这个问题的方法。请查看。

使用set和&。将n=n+1行移动到“if”条件之外的循环末尾。如果“If”条件失败,则n永远不会增加,循环继续on@Dinesh.hmn请参阅中的edit1question@YOU每次比赛我都需要
计数器
。如何使用
set
&
获取计数器?列表从0到n-1。如果你输入list[n],它会给你一个错误,说list index out out range@Harry,谢谢你用优雅的方式编写它。从他的代码中,我看到的是一个刚刚开始的人,所以我不想用高级代码让他难堪,所以我对你的答案投了赞成票。是的,这就是为什么我对你的答案投了反对票。但我还是想把它写下来供他将来参考:)
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
List1= ['john', 'doe','sima', 'alina' ]
List2=[]
test = "John is with Doe but alina is alone today."
List2 = test.lower().split()
counter = 0
for word in List1:
    try:
        index_number = List2.index(word)
        counter += 1
        print("Matched : " + str(counter) + " " +  word + " at " + str(index_number))
    except:
        print("No Match Found")