繁体   English   中英

如何使用Python dict动态创建树

[英]How can I dynamically create a tree using Python dict

我将使用python dict创建一棵树,而在执行之前不知道级别和节点的确切数目。

例如,我要循环许多具有3个属性的项目:大小,颜色和重量。 在每个循环中,我执行以下操作

item_data = {}
for item in items:
    size, color, weight = item.get_attr()
    if size not in item_data:
        item_data[size] = {}
    if color not in item_data[size]:
        item_data[size][color] = {}
    if weight not in item_data[size][color]:
        item_data[size][color][weight] = []
    # Do something to the tree...

最后我得到这样的字典

item_data == {'L':{
                  'red':{45:[...], 
                         50:[...]}, 
                  'green':{
                         40:[...]}}, 
              'XL':{...}}

但这并不灵活。 例如,如果我要添加另一个属性,例如“价格”? 我必须知道,如果在上面的代码中再添加一个。

我正在考虑通过以下方式进行操作,但不知道如何在几行中完成操作

attrs = [item.get_attr()]
for attr in attrs:
    # Create the tree here..

提前致谢!

在这里查看networkx是否相关。 否则,这是一个基本版本,扩展了您使用attr循环的想法(未经测试的代码)。

for item in items:
    tree = item_data
    for i,attr in enumerate(item.get_attr()):
        if attr not in tree.keys():
            if i<len(item.get_attr())-1:
                tree[attr] = {}
            else:
                tree[attr] = []
        else:
            tree = tree[attr]
    # do something to the tree

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM