簡體   English   中英

Python:else語句返回True,盡管其中提到返回False

[英]Python: else statement returns True, though it's mentioned to return False

我正在編寫一個函數,該函數驗證作為參數傳遞的兩個列表,如果兩個列表的結構相同,則返回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”

如果內部列表不匹配,則不會返回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

否則,您會“檢測/打印”錯誤,但永遠不會采取行動。

修復它的最簡單方法是簡單地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]))

產生正確的:

我在上一篇文章中畫了一張圖來解釋這種情況

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM