如何使用 Python 创建变体树



我想评估给定数量的特征和相应属性存在多少个变体,然后将这些组合绘制为分支树,其中每个分支代表一个组合/变体。

例:特点:颜色,大小,暗淡。每个要素都有不同的属性(颜色:红色、绿色、蓝色;大小:大、小(。

通过排列,我找到了变体的数量。每个组合/变体都是我的变体树的一个分支。例如('red', 'big', 1( 是一个分支,('red', 'big', 2( 是另一个分支,依此类推。

有没有库可以帮助我用节点和弧线绘制这些分支?

排列代码:

colors = ['red', 'green', 'blue']
size = ['big','small']
dim = [1,2,3]
from itertools import product
x =list (product(colors,size,dim))
print (x)
print ("Number of variants:",len(x))
[('red', 'big', 1), ('red', 'big', 2), ('red', 'big', 3), 
 ('red', 'small', 1), ('red', 'small', 2), ('red', 'small', 3), 
 ('green', 'big', 1), ('green', 'big', 2), ('green', 'big', 3), 
 ('green', 'small', 1), ('green', 'small', 2), ('green', 'small', 3), 
 ('blue', 'big', 1), ('blue', 'big', 2), ('blue', 'big', 3), 
 ('blue', 'small', 1), ('blue', 'small', 2), ('blue', 'small', 3)]

在此处输入图像描述

我能够使用通用图形描述格式DOT创建它。创建 DOT 文件main.py Python 文件:

from itertools import product
colors = ['red', 'green', 'blue']
size = ['big','small']
dim = [1,2,3]
print('digraph G {n    rankdir=LRn    node [shape=box]n')
print('    start [label=""]')
for i, c in enumerate(colors):
    print(f'    color_{i} [label="{c}"]; start -> color_{i}')
    for j, s in enumerate(size):
        print(f'    size_{i}_{j} [label="{s}"]; color_{i} -> size_{i}_{j}')
        for k, d in enumerate(dim):
            print(f'    dim_{i}_{j}_{k} [label="{d}"]; size_{i}_{j} -> dim_{i}_{j}_{k}')
print('}')

我使用以下命令创建了映像:

$ python main.py > graph.dot
$ dot -Tpng graph.dot -o graph.png

我使用的 dot 命令来自 graphviz 包。我没有经常使用DOT,所以我无法添加文本和蓝色。

最新更新