python - Python 中的递归列表相等

标签 python list recursion

我正在尝试编写一个程序,使用递归来判断两个列表是否完全相同,当列表不相同时它可以工作,但是当它们相同时,它会给出一个错误,指出列表索引已超出的范围。按照我编写的方式,我直接比较列表(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

最佳答案

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

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

关于python - Python 中的递归列表相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35900443/

相关文章:

python - Django BigInteger自动增量字段作为主键?

python - Django 模板和 HTML 框架集

python - 如何通过curl向couchDB中插入数百万文档?

python - Python 比较两个字符串列表

python - 按值求和列表

python - 在 python 中构建对象列表以进行矢量化 : Can a list of structures(objects) be vectorized, 或者需要显式数组

python - 递归返回错误的列表列表

python-3.x - 在 Python 3 中自动测试反向字符串

javascript - 我在用 JavaScript 编写递归函数时遇到问题 - 它似乎没有正确地将 "fall back"到更小的深度

java - 在对键排序后对列表进行排序