python 字典生成树状图

from graphviz import Digraph


# 获取所有节点中最多子节点的叶节点
def getMaxLeafs(myTree):
    numLeaf = len(myTree.keys())
    for key, value in myTree.items():
        if isinstance(value, dict):
            sum_numLeaf = getMaxLeafs(value)
            if sum_numLeaf > numLeaf:
                numLeaf = sum_numLeaf
    return numLeaf


def plot_model(tree, name):
    g = Digraph("G", filename=name, format='png', strict=False)
    first_label = list(tree.keys())[0]
    g.node("0", first_label)
    _sub_plot(g, tree, "0")
    leafs = str(getMaxLeafs(tree) // 10)
    g.attr(rankdir='LR', ranksep=leafs)
    g.view()


root = "0"


def _sub_plot(g, tree, inc):
    global root

    first_label = list(tree.keys())[0]
    ts = tree[first_label]
    for i in ts.keys():
        if isinstance(tree[first_label][i], dict):
            root = str(int(root) + 1)
            g.node(root, list(tree[first_label][i].keys())[0])
            g.edge(inc, root, str(i))
            _sub_plot(g, tree[first_label][i], root)
        else:
            root = str(int(root) + 1)
            g.node(root, tree[first_label][i])
            g.edge(inc, root, str(i))


tree = {
        "tearRate": {
            "reduced": "no lenses",
            "normal": {
                "astigmatic": {
                    "yes": {
                        "prescript": {
                            "myope": "hard",
                            "hyper": {
                                "age": {
                                    "young": "hard",
                                    "presbyopic": "no lenses",
                                    "pre": "no lenses"
                                }
                            }
                        }
                    },
                    "no": {
                        "age": {
                            "young": "soft",
                            "presbyopic": {
                                "prescript": {
                                    "myope": "no lenses",
                                    "hyper": "soft"
                                }
                            },
                            "pre": "soft"
                        }
                    }
                }
            }
        }
    }
plot_model(tree, "tree.gv")

效果如下:
在这里插入图片描述

  • 6
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
### 回答1: Python 字典生成式(Dictionary Comprehension)可以用一种简洁的语法来创建字典。 基本语法如下: ```python {key:value for key, value in iterable} ``` 其中,`key` 和 `value` 分别表示字典中的键和值,`iterable` 是一个可迭代对象,可以是列表、元组、集合等。通过遍历 `iterable` 中的元素,将每个元素赋值给 `key` 和 `value`,从而生成一个字典。 例如,我们可以通过以下代码创建一个字典,其中键为 1~5 的数字,值为对应数字的平方: ```python d = {i: i**2 for i in range(1, 6)} print(d) ``` 输出结果为: ``` {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} ``` 除了上述基本语法外,字典生成式还可以添加条件表达式。例如,我们可以通过以下代码创建一个字典,其中键为 1~10 的数字,值为对应数字的平方,但只保留值为偶数的项: ```python d = {i: i**2 for i in range(1, 11) if i % 2 == 0} print(d) ``` 输出结果为: ``` {2: 4, 4: 16, 6: 36, 8: 64, 10: 100} ``` ### 回答2: Python字典生成式是一种快速简洁地生成字典的方法,类似于列表生成式。 字典生成式的基本语法为: {key_expression: value_expression for item in iterable if condition} 其中,key_expression表示生成字典的键的表达式,value_expression表示生成字典的值的表达式,item表示可迭代对象的元素,iterable表示可迭代对象,condition表示一个选择条件。 与列表生成式类似,字典生成式可以包含多个for循环和if条件语句。生成字典中的键和值是通过表达式计算得到的。 下面是一个例子: 假设有一个列表numbers = [1, 2, 3, 4, 5],我们想生成一个字典字典的键是列表中的数字,值是数字的平方。 我们可以使用字典生成式来实现: numbers_dict = {num: num**2 for num in numbers} 执行以上代码后,会得到一个字典numbers_dict,其中包含如下键值对: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} 这个字典的键为列表numbers中的数字,值为对应数字的平方。 使用字典生成式可以简洁地生成字典,并且可以根据需要添加多个for循环和if条件语句来筛选和计算生成的键值对。 ### 回答3: Python 字典生成式是一种简洁而又高效的创建字典的方法。它类似于列表生成式,但使用花括号 {} 来表示字典字典生成式的语法为: {key: value for key, value in iterable} 其中,key 是字典中的键,value 是对应的值,iterable 是一个可迭代对象,例如列表、元组、集合等。 我们可以通过迭代 iterable 中的元素,并使用 key 和 value 初始化字典中的对应键值对。字典生成式在遍历 iterable 中的元素时非常方便,可以根据需要自定义键值对的规则。 下面是一个具体的示例: numbers = [1, 2, 3, 4, 5] squared_dict = {num: num**2 for num in numbers} print(squared_dict) 输出: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} 在上面的示例中,我们通过一个列表生成式创建了一个字典。遍历 numbers 列表中的元素,为每个元素生成一个键值对,其中键为元素本身,值为元素的平方。 除了简单的映射规则外,字典生成式还可以通过添加条件语句实现更为复杂的筛选和转换。 例如: numbers = [1, 2, 3, 4, 5] even_squares = {num: num**2 for num in numbers if num % 2 == 0} print(even_squares) 输出: {2: 4, 4: 16} 在这个例子中,只有当元素为偶数时,才将其平方添加到字典中。 通过使用字典生成式,我们可以以一种简洁且易读的方式来创建和操作字典,提高代码的可读性和效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值