【发布时间】:2017-11-27 17:02:18
【问题描述】:
我有一棵树,我正在使用映射方法遍历树(即具有相似键的节点必须聚集在一起)假设根节点标记为 0,根节点的左侧为 -1,根节点的右侧为 +1。遍历整棵树,将每个节点的HD(与根的水平距离)赋值为节点的key,将节点的数据赋值为value。现在我想在字典中的一个位置附加所有具有相似键的值,例如 {0: ['10','13'], 1: ['12'], -2: ['12'], -1: ['11']} 用于下面创建的树。
代码
class node:
dict1={}
def __init__(self,data):
self.data=data
self.left=None
self.right=None
def check_if_exists(self,hd,root):
if not self.dict1:
self.dict1[hd] = [root.data]
else:
if hd in self.dict1.keys(): ###Checking if key already exists for some node
self.dict1[hd].append(root.data)
else:
self.dict1[hd] = [root.data]
def vertical_order_tree(self,root,hd):
if root:
self.check_if_exists(hd,root)
self.vertical_order_tree(root.left,hd-1)
self.vertical_order_tree(root.right,hd+1)
root=node("10")
root.left=node("11")
root.left.left=node("12")
root.right=node("12")
#root.right.left=node("13")
root.vertical_order_tree(root,0)
print(root.dict1)
输出:
self.dict1[hd].append(root.data)
AttributeError: 'str' object has no attribute 'append'
附加相似的值会导致问题。任何人都可以在这里捕获错误。我不擅长处理字典。
【问题讨论】:
-
错误提示
self.dict1[hd]是一个字符串,而你认为它是一个列表。您不能附加到字符串。 -
是的,我知道,但是在哪里以及改变什么对我来说是个问题。所以一个正确的代码可以在这里帮助我
-
将
if not self.dict1:中的self.dict1[hd] = root.data替换为self.dict1[hd] = [root.data]。您错误地在字典中插入了字符串而不是列表。 -
{0: ['13'], 1: ['12'], -2: ['12'], -1: ['11']} 被替换后@VasilisG。 10 被 13 覆盖
-
我忘记提及的另一个更改是:删除
for k,v in self.dict1.items(): if k==hd:并简单地输入if hd in self.dict1.keys():。请参阅问题中的编辑。
标签: python dictionary data-structures tree