我有一个`dict`对象,我想要计算特定命名的`values`的总和和平均值。
设置:
现在我有了`dict`对象,我该怎么做呢:
1. 获取所有叶子节点的数量? 2. 获取所有叶子节点的平均宽度和平均高度?
我可以通过以下方式访问值并遍历树结构:
所以我可以使用嵌套的for循环来完成这个任务。
但是有没有更好的方法呢?
设置:
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`对象,我该怎么做呢:
1. 获取所有叶子节点的数量? 2. 获取所有叶子节点的平均宽度和平均高度?
我可以通过以下方式访问值并遍历树结构:
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
leaves = [leaf for tree in tree-dict['trees'] for branch in tree['branches'] for leaf in branch['leaves']]
;当然,leafcount = len(leaves)
。 - undefined