簡體   English   中英

在遞歸遍歷列表並將值與字典匹配時遇到關鍵錯誤,Python

[英]Getting key error while iterating through a list recursively and matching value to a dictionary, Python

我的函數在以下輸入interpret(["NOT", "true"], {"NOT": "false"})失敗interpret(["NOT", "true"], {"NOT": "false"})

基本上,該函數與“創建自己的”邏輯值運算符有關,如果列表中的值與字典中的鍵匹配,則解釋它們。 我在這里收到KeyError: "true" ,但我不知道如何解決。

我在做遞歸錯誤嗎? 在這種情況下,它應該返回“ false”,因為“ NOT”等於“ false”,但是在其他情況下,如果您知道我的意思,它應該作為普通的非運算符函數起作用。

我的功能代碼:

def interpret(logicalExpression, interpretation):
    if type(logicalExpression) is str:  #
        if not interpretation:
            return logicalExpression
        return interpretation[logicalExpression]
    elif len(logicalExpression) == 1:
        return interpret(logicalExpression[0], interpretation)
    elif logicalExpression[1] == "OR" and len(logicalExpression) >= 3:
        if interpret(logicalExpression[0], interpretation) == "true" or interpret(logicalExpression[2:], interpretation) == "true":
            return "true"
        else:
            return "false"
    elif logicalExpression[1] == "AND" and len(logicalExpression) >= 3:
        if interpret(logicalExpression[0], interpretation) == "true" and interpret(logicalExpression[2:], interpretation) == "true":
            return "true"
        else:
            return "false"

    if logicalExpression[0] == "NOT" and len(logicalExpression) == 2:
        if interpret(logicalExpression[1:], interpretation) == "false":
            return "true"
        else:
            return "false"

錯誤出在您的輸入中。

您在logicalExpression中傳遞"true" ,但在解釋中未傳遞"true" KeyError是正確的行為。

我想你想通過類似的解釋 {"true": "true", "false": "false"}

>>> interpret(["NOT", "true"], {"true": "true", "false": "false"})
'false'

暫無
暫無

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

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