【发布时间】:2020-11-19 10:20:37
【问题描述】:
我遇到了一个导致错误的旧 python 2x 代码语法问题:
print (name, tree.keys()[0])
TypeError: 'dict_keys' object is not subscriptable
而旧的 python 2x 代码是:
def printTree(self,tree,name):
if type(tree) == dict:
print name, tree.keys()[0]
for item in tree.values()[0].keys():
print name, item
self.printTree(tree.values()[0][item], name + "\t")
else:
print name, "\t->\t", tree
如何在使用 python 3x 时更改这些语法?我试过 list() 怎么self.printTree(tree.values()[0][item], name + "\t") 仍然有 dict_value 错误。
完整代码:https://homepages.ecs.vuw.ac.nz/~marslast/Code/Ch12/dtree.py
感谢您的帮助。
【问题讨论】:
-
你的问题出在 python 3x 上,对吧?所以我认为共享 python 2 代码实际上是无关紧要的。为什么不发布实际上破坏并给出错误的python 3代码?
-
dict.keys()在 python 3 中没有返回列表,因为它在 python 2 中使用过,因此出现错误。将tree.keys()包装为list(tree.keys())或使用解包概括[*tree][0]。另见stackoverflow.com/a/45253740/909252 -
我已将
print (name, tree.keys()[0])更改为print (name, [*tree][0])。但是,for item in [*tree].values()[0]:仍然会带出错误AttributeError: 'list' object has no attribute 'values' -
在这种情况下,
[*tree]是一个列表,因此没有values方法。tree是一本字典。学习决策树很有趣,但在学习更多 Python 之后,您可能会从中得到更多!
标签: python