我有一个
dict
对象,我想从中计算特定名称 values
的 sum 和 mean。
设置:
tree_str = """{
'trees': [
{
'tree_idx': 0,
'dimensions': (1120, 640),
'branches': [
'leaves': [
{'geometry': [[0.190673828125, 0.0859375], [0.74609375, 0.1181640625]]},
{'geometry': [[0.1171875, 0.1162109375], [0.8076171875, 0.15625]]}
],
'leaves': [
{'geometry': [[0.2197265625, 0.1552734375], [0.7119140625, 0.1943359375]]},
{'geometry': [[0.2060546875, 0.1923828125], [0.730712890625, 0.23046875]]}
]
]
}
]
}"""
tree_dict = yaml.load(tree_str, Loader=yaml.Loader)
地点:
# assume for the sake of coding
{'geometry': ((xmin, ymin), (xmax, ymax))}
# where dimensions are relative to an image of a tree
现在我有了
dict
对象,我该怎么办:
count
?average width
和average height
所有叶子吗?我可以使用以下方法访问值并遍历树:
tree_dict['trees'][0]['branches'][0]['leaves'][0]['geometry'][1][1]
所以我可以使用嵌套 for 循环来做到这一点:
leafcount = 0
leafwidth = 0
leafheight = 0
sumleafwidth = 0
sumleafheight = 0
avgleafwidth = 0
avgleafheight = 0
for tree in tree_dict['trees']:
print("TREE")
for branch in tree['branches']:
print("\tBRANCH")
for leaf in branch['leaves']:
leafcount += 1
(lxmin, lymin), (lxmax, lymax) = leaf['geometry']
leafwidth = lxmax - lxmin
leafheight = lymax - lymin
print("\t\tLEAF: x1({}), y1({}), x2({}), y2({})\n\t\t\tWIDTH: {}\n\t\t\tHEIGHT: {}".format(lxmin, lymin, lxmax, lymax, leafwidth, leafheight))
sumleafwidth += lxmax - lxmin
sumleafheight += lymax - lymin
avgleafwidth = sumleafwidth / leafcount
avgleafheight = sumleafheight / leafcount
print("LEAVES\n\tCOUNT: {}\n\tAVERAGE WIDTH: {}\n\tAVERAGE HEIGHT: {}".format(leafcount, avgleafwidth, avgleafheight))
但是还有更好的办法吗?
# psuedo code
leafcount = count(tree_dict['trees'][*]['branches'][*]['leaves'][*])
leaves = (tree_dict['trees'][*]['branches'][*]['leaves'][*])
sumleafwidth = sum(leaves[*]['geometry'][1][*]-leaves[*]['geometry'][0][*])
sumleafheight = sum(leaves[*]['geometry'][*][1]-leaves[*]['geometry'][*][0])
avgleafwidth = sumleafwidth / leafcount
avgleafheight = sumleafheight / leafcount
我认为,尽管 python dict 在大多数情况下可以用作树表示,但如果您想处理更高级的与树相关的任务,如上所述,它并不是最好的数据结构。 python中有很多树状结构的实现,例如treelib。 您可以从字典移动到树,例如像这样:
def dict_to_tree(data, parent_node=None, tree=None):
if tree is None:
tree = Tree()
for key, value in data.items():
if isinstance(value, dict):
# Create a node for the key
tree.create_node(tag=key, identifier=key, parent=parent_node)
# Recursively call the function to process the sub-dictionary
dict_to_tree(value, parent_node=key, tree=tree)
else:
# Create a node for the key and value
tree.create_node(tag=f"{key}: {value}", identifier=key, parent=parent_node)
return tree
您应该能够在正确的数据结构上以更简单、更优雅的方式解决您的问题。