Python:else语句返回True,尽管其中提到返回False

时间:2019-05-15 19:40:11

标签: python python-3.x

我正在编写一个函数,该函数验证作为参数传递的两个列表,如果两个列表的结构相同,则返回True,否则返回False。

尝试在代码的多个位置使用打印语句,但没有发现问题。对于不同的结构列表,其他语句按预期方式输出“ False”,但是奇怪的是,该函数返回True,尽管它应该返回False。

def same_structure_as(original,other):
    if isinstance(original, list) and isinstance(other, list):
        if len(original) == len(other):
            for el in original:
                if isinstance(el, list):
                    orig_new = original[original.index(el)]
                    other_new = other[original.index(el)]
                    same_structure_as(orig_new,other_new)
            return True
        else:
            return False
    else:
        print("False")
        return False

same_structure_as([1,[1,1]],[[2,2],2])

由于两个输入列表的结构不同,因此代码应返回False。 print语句正确打印“ False”,但即使我给出“ return False”也返回“ True”

2 个答案:

答案 0 :(得分:4)

如果内部列表不匹配,则不会返回False:

def same_structure_as(original,other):
    if isinstance(original, list) and isinstance(other, list):
        if len(original) == len(other):
            for el in original:
                if isinstance(el, list):
                    orig_new = original[original.index(el)]
                    other_new = other[original.index(el)]
                    same_structure_as(orig_new,other_new) # here - the result is ignored
            return True
        else:
            return False
    else:
        print("False")
        return False

您需要

def same_structure_as(original,other):
    if isinstance(original, list) and isinstance(other, list):
        if len(original) == len(other):
            for el in original:
                if isinstance(el, list):
                    orig_new = original[original.index(el)]
                    other_new = other[original.index(el)]
                    if not same_structure_as(orig_new,other_new): # early exit if not same 
                        return False
                     # else continue testing (no else needed - simply not return anything)
            return True
        else:
            return False
    else:
        print("False")
        return False

否则,您会“检测/打印”错误,但永远不会采取行动。

答案 1 :(得分:1)

最简单的解决方法是简单地return递归函数(我确定这是您的意图):

def same_structure_as(original, other):
    if isinstance(original, list) and isinstance(other, list):
        if len(original) == len(other):
            for el in original:
                if isinstance(el, list):
                    orig_new = original[original.index(el)]
                    other_new = other[original.index(el)]
                    return same_structure_as(orig_new, other_new) # just add a return here
            return True
        else:
            return False
    else:
        print("False")
        return False

print(same_structure_as([1,[1,1]],[[2,2],2]))

正确无误:

  

错误

     

错误

drew a diagram在上一篇文章中解释了这种情况