我有一本字典,其中包含子字典。这是一个具有节点,一些叶节点和一些非叶节点的决策树。在给定字典的情况下,我该如何计数?
例如:
{'Outlook': {'Overcast': 'Yes', 'Rain': {'Wind': {'Strong': 'No', 'Weak': 'Yes'}}, 'Sunny': {'Humidity': {'High': 'No', 'Normal': 'Yes'}}}}
这将生成如下树:
其中有三个非叶节点和五个叶节点。我对如何做到有个大致了解:
def count(d):
a, b = 0, 0 # non-leaf nodes and leaf nodes
for key, value in d.items():
if isinstance(value, dict):
a += 1
# some recursive call on value
else:
b+= 1
return a, b
但是我不确定如何组织递归调用。有内置方法吗?
答案 0 :(得分:3)
您可以轻松完成
def count(d):
a, b = 0, 0 # subdicts and not-subdicts
for key, value in d.items():
if isinstance(value, dict):
a += 1
suba, subb = count(value)
a += suba
b += subb
else:
b += 1
return a, b
但是,您的示例包含五个“非词典”和五个“词典”。
答案 1 :(得分:1)
这是您要寻找的:
def get_count(d, c = {0:0, 1:0}):
c[0]+=1 #count non-leaf nodes
nodes = d.keys()
for node in nodes:
subnodes = d[node].values()
for subnode in subnodes:
if isinstance(subnode, dict)
get_count(subnode,c)
else:
c[1]+=1 #count leaf nodes
return c
d = {'Outlook': {'Overcast': 'Yes', 'Rain': {'Wind': {'Strong': 'No', 'Weak': 'Yes'}}, 'Sunny': {'Humidity': {'High': 'No', 'Normal': 'Yes'}}}}
print(get_count(d))
输出:3,5
3:非叶节点数
5:否。叶节点的数量
答案 2 :(得分:1)
一种可能性是创建一个运行中的字典来存储计数:
def get_count(d, c):
for a, b in d.items():
c[isinstance(b, dict)] += 1
if isinstance(b, dict):
get_count(b, c)
d = {'Outlook': {'Overcast': 'Yes', 'Rain': {'Wind': {'Strong': 'No', 'Weak': 'Yes'}}, 'Sunny': {'Humidity': {'High': 'No', 'Normal': 'Yes'}}}}
c = {0:0, 1:0}
get_count(d, c)
print(c)
输出:
{0: 5, 1: 5}
#0: elements, #1: sub-dictionaries