首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >递归迭代列表并将值匹配到字典时出现键错误,Python

递归迭代列表并将值匹配到字典时出现键错误,Python
EN

Stack Overflow用户
提问于 2017-10-09 19:43:42
回答 1查看 214关注 0票数 0

我的函数在以下输入interpret(["NOT", "true"], {"NOT": "false"})处失败

基本上,该函数用于“创建我自己的”逻辑值操作符,并在列表中的值与字典中的键匹配时解释它们。我在这里找到了KeyError: "true",但我不知道如何修复它。

我是不是做错了递归?它应该返回"false“,因为" not”在这种情况下等于"false“,但在其他情况下,它应该作为正常的not运算符函数运行,如果你明白我的意思的话。

我的函数的代码:

代码语言:javascript
复制
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"
EN

回答 1

Stack Overflow用户

发布于 2017-10-09 21:18:20

错误在您的输入中。

在logicalExpression中传递"true",但在解释中不传递"true"。KeyError是正确的行为。

我认为你想通过像{"true": "true", "false": "false"}这样的解释

代码语言:javascript
复制
>>> interpret(["NOT", "true"], {"true": "true", "false": "false"})
'false'
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46645643

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档