【问题标题】:Python Name Error 'Name' is not defined within nested dictionaryPython 名称错误“名称”未在嵌套字典中定义
【发布时间】:2019-12-20 17:25:37
【问题描述】:

我正在通过嵌套字典创建决策树,但出现错误

11:{'Q':'咖啡还是茶?', 'A':{'Coffee': 咖啡, 'Tea': 茶}}, NameError:名称“咖啡”未定义。当我注释掉字典 11 时,我遇到了错误

12:{'Q':'冰咖啡还是冰茶?', 'A': {'IcedCoffee:': IcedCoffee, '冰茶': IcedTea}}, NameError: 名称“IcedCoffee”未定义

我错误地引用了前一个值字典中的字典?

#Decision tree implemented as nested linked dictionary
decision_tree_1 = {


0:{'Q':'Would you like to order?', 'A':{'Yes': 1, 'No': 2}},
1:{'Q':'Category ?', 'A':{'Hot Drink': 11, 'Cold Drink': 12,'Food': 13}},
11:{'Q':'Coffee or tea?', 'A':{'Coffee': Coffee, 'Tea': Tea}},
12:{'Q':'Iced Coffee or Iced Tea?', 'A': {'IcedCoffee:': IcedCoffee, 'Iced Tea': IcedTea}},
13:{'Q':'Sandwich or Pastry', 'A': {'Sandwich': Sandwich, 'Pastry': Pastry}},

S:{'Q':'What size?', 'A':{'Small': S1, 'Medium': M,'Large': L}},

Q:{'Q':'What quantity?', 'A':{'1': One, '2': Two,'3': Three}},

Coffee:{'Q':'Coffee', 'A':{}},
Tea:{'Q':'Tea', 'A':{}},
IcedCoffee:{'Q':'Iced Coffee', 'A':{}},
IcedTea:{'Q':'Iced Tea', 'A':{}},
Sandwich:{'Q':'Sandwich', 'A':{}},
Pastry:{'Q':'Pastry', 'A':{}},

S1:{'Q':'Small', 'A':{}},
M:{'Q':'Medium', 'A':{}},
L:{'Q':'Large', 'A':{}},

One:{'Q':'1', 'A':{}},
Two:{'Q':'2', 'A':{}},
Three:{'Q':'3', 'A':{}},

}

【问题讨论】:

  • 嗯,它没有定义。那么你期待什么呢?
  • 我没有在 Coffee:{'Q':'Coffee', 'A':{}}, 行中定义吗?
  • 不,这不是变量,dict 键是可散列的对象,它们不会成为变量。事实上,这也会抛出一个NameError,只是在解析dict字面量的过程中还没有到达那个部分
  • 你有'IcedCoffee:',但我想应该是'Iced Coffee'
  • 您必须使用Coffee = ... 创建变量。使用Coffee:{'Q':'Coffee', 'A':{}} 无法创建变量Coffee。您应该首先使用字符串"Coffee" 而不是变量Coffee 创建"Coffee":{'Q':'Coffee', 'A':{}},然后在其他地方使用decision_tree_1["Coffee"] - 即。 'A':{'Coffee': decision_tree_1["Coffee"],`

标签: python python-3.x dictionary data-structures tree


【解决方案1】:

Barewords,即文件中的一些字母,如 Coffee,只有在它们是赋值语句的一部分或之前已绑定到某个值时才是有效的 Python 表达式。

我认为您在这里尝试构建的那种自我引用结构并不能很好地由带有字符串键的 python dict 提供。您可能应该考虑创建某种 DecisionTree 类,以便其节点可以按照您想要的方式相互引用。

【讨论】:

【解决方案2】:

这是您的决策树的一个子集,缩进效果更好,仅显示与咖啡相关的内容:

dt = {
  11:{
    'Q':'Coffee or tea?', 
    'A':{'Coffee': Coffee, 'Tea': Tea}
  },
  Coffee:{
    'Q':'Coffee', 
    'A':{}
  }
}

不幸的是,这将得到一个NameError,因为当您在第 4 行第一次使用 Coffee 时,您还没有定义它。然后您尝试在第 6 行定义它,但出于同样的原因,这也会给出 NameError

您可以通过引用第二个 Coffee 来定义某些内容,但我认为您应该将 Coffee 定义移到决策树之外。

coffee = {
  'Q':'Coffee', 
  'A':{}
}
tea = ...

dt = {
  11:{
    'Q':'Coffee or tea?', 
    'A':{'Coffee': coffee, 'Tea': tea}
  },
  ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-23
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 2016-04-02
    • 2022-01-01
    • 2019-11-13
    相关资源
    最近更新 更多