【问题标题】:How can I create a variant tree using Python?如何使用 Python 创建变体树?
【发布时间】:2017-04-05 12:01:23
【问题描述】:

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

示例: 特点:颜色、大小、暗淡。每个特征都有不同的属性(颜色:红、绿、蓝;尺寸:大、小)。

通过排列,我找到了变体的数量。每个组合/变体都是我的变体树的一个分支。例如。 ('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)]

enter image description here

【问题讨论】:

  • 在您的示例图像中为什么只为红色/大分支显示暗淡?
  • dim 仅用于一个示例,但也会出现在其他颜色/尺寸组合中。

标签: python graph tree permutation


【解决方案1】:

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

from itertools import product

colors = ['red', 'green', 'blue']
size = ['big','small']
dim = [1,2,3]

print('digraph G {\n    rankdir=LR\n    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

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

【讨论】:

    猜你喜欢
    • 2014-02-13
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 2021-03-15
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多