使用递归Python实现列表相等

使用递归Python实现列表相等,python,list,recursion,Python,List,Recursion,我试图编写一个程序,通过递归判断两个列表是否完全相同。当列表不相同时,它可以工作,但当它们相同时,它会给我一个错误,告诉我列表索引超出范围。以我编写它的方式,我不是直接比较列表(lst1==lst2)。我只是比较列表中的单个元素和列表的长度 def compare (lst1, lst2): if len(lst1) != len(lst2): return False if lst1[0] != lst2[0]: return False

我试图编写一个程序,通过递归判断两个列表是否完全相同。当列表不相同时,它可以工作,但当它们相同时,它会给我一个错误,告诉我列表索引超出范围。以我编写它的方式,我不是直接比较列表(lst1==lst2)。我只是比较列表中的单个元素和列表的长度

def compare (lst1, lst2):
    if len(lst1) != len(lst2):
        return False
    if lst1[0] != lst2[0]:
        return False
    return compare(lst1[1:],lst2[1:])
例如:

>>> compare(['ispython',1,2,3], ['isPYthon',1,2,3])
False
>>> compare(['ispython',1,2,3], [1,2,3])
False
>>> compare(['ispython',1,2,3], ['ispython',1,2,3])
True

你错过了一个案子。在比较了两个列表的最后一个元素之后,您仍然会调用
compare(lst1[1:]…
,即使没有剩下任何内容,因此下一次调用的
lst1[0]
将在一个空列表中查找

您需要对此进行检查,并在检查之前实际返回True:

if len(lst1) == len(lst2) == 0:
    return True

您需要一个基本情况。您的逻辑几乎正确,只是在递归上没有退出点。如果输入一个空列表,会发生什么

if len(lst1) != len(lst2):
    return False
每个列表的长度为0,因此它不会返回此处

if lst1[0] != lst2[0]:
    return False
lst1[0]
不存在,lst2[0]也不存在,这就是发生索引错误的地方。请尝试添加以下内容:

if len(lst1) == 0 == len(lst2) == 0:
    return True
试试这个:

def compare (lst1, lst2):
    if lst1 and lst2:
        if len(lst1) != len(lst2):
            return False
        if lst1[0] != lst2[0]:
            return False
        return compare(lst1[1:],lst2[1:])
    else:
        return True