0

在这里,我得到了一个字符串列表:

['2-3-1-*-*','2-3-*-*-*','2-1-*-*-*','1-4-3-*-*','2-3-2-*-*','2-1-3-*-*','1-1-*-*-*','2-3-1-1-*'];

我正在尝试将此字符串分组为如下结构:

--'2-3-*-*-*' 
   --'2-3-1-*-*'
      --'2-3-1-1-*'
   --'2-3-2-*-*'
--'2-1-*-*-*'
   --'2-1-3-*-*'
--'1-4-3-*-*'
--'1-1-*-*-*'

这就像树状结构。我是编程的初学者,所以有人可以给我一个提示,告诉我如何构建树状结构以及我可以使用的任何合适的结构吗?

4

2 回答 2

1

如果您使用一些 js 库来呈现它,请将其保存为嵌套dict,以便可以轻松地将其导出为 JSON。

def parser(items):
    nested_dicts = {}

    for item in items:
        nodes = item.split('-')
        current_dict = nested_dicts
        for n in nodes[:-1]:
            current_dict = current_dict.setdefault(n, {})

        last = nodes[-1]
        current_dict[last] = current_dict.get(last, 0) + 1

    return nested_dicts

带有提供数据的示例输出:

{
  "1": {
    "1": {
      "*": {
        "*": {
          "*": 1
        }
      }
    }, 
    "4": {
      "3": {
        "*": {
          "*": 1
        }
      }
    }
  }, 
  "2": {
    "1": {
      "3": {
        "*": {
          "*": 1
        }
      }, 
      "*": {
        "*": {
          "*": 1
        }
      }
    }, 
    "3": {
      "1": {
        "1": {
          "*": 1
        }, 
        "*": {
          "*": 1
        }
      }, 
      "2": {
        "*": {
          "*": 1
        }
      }, 
      "*": {
        "*": {
          "*": 1
        }
      }
    }
  }
}
于 2013-10-21T03:15:28.550 回答
1
s = ['2-3-1-*-*','2-3-*-*-*','2-1-*-*-*','1-4-3-*-*','2-3-2-*-*','2-1-3-*-*','1-1-*-*-*','2-3-1-1-*']

def isSubElement(subelement, element):
    return (subelement != element) and all([(e1 == e2) or (e1 == "*" and e2 != "*") for e1, e2 in zip(element.split('-'), subelement.split('-'))])

def parseTree(elementList):
    if len(elementList) == 0:
        return {}
    elements = elementList[:]
    d = {}
    for element1 in elements:
        parent = True
        for element2 in elements:
            if isSubElement(element1, element2):
                parent = False
                break
        if parent:
            d[element1] = {}
    for element1 in d.keys():
        d[element1] = parseTree([element for element in elements if isSubElement(element, element1)])
    return d

print parseTree(s)

输出:

{'2-1-*-*-*': 
    {'2-1-3-*-*': 
        {}},  
'1-4-3-*-*': 
    {},  
'1-1-*-*-*': 
    {},  
'2-3-*-*-*': 
    {'2-3-1-*-*': 
        {'2-3-1-1-*': 
            {}}, 
    '2-3-2-*-*': 
        {}}}
于 2013-10-21T03:21:33.737 回答