Skip to main content
 首页 » 编程设计

Python:else 语句返回 True,尽管它被提到返回 False

2025年05月04日20davidwang456

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

尝试在代码的多个位置使用 print 语句,没有发现任何问题。对于不同的结构列表,Else 语句按预期打印“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”,但返回“True”,即使我给出“return False”

请您参考如下方法:

如果内部列表不匹配,您不会返回 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 

否则你“检测/打印”错误但从不采取行动。